Function execution flow in Go - Time & Space Complexity
When we look at how a function runs, we want to know how long it takes as the input grows.
We ask: How does the work inside the function increase when input changes?
Analyze the time complexity of the following code snippet.
func sum(numbers []int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
This function adds up all numbers in a list and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number to total inside a loop.
- How many times: Once for every number in the list.
As the list gets bigger, the function does more additions, one for each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "The function runs in the same time no matter how many numbers there are."
[OK] Correct: Because the function must add each number, more numbers mean more work.
Understanding how function steps grow with input helps you explain your code clearly and think about efficiency.
"What if we changed the function to sum only the first half of the list? How would the time complexity change?"