Return values in Go - Time & Space Complexity
We want to understand how the time it takes to run code with return values changes as the input grows.
Specifically, how does returning values affect the work done by the program?
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 sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list once.
- How many times: Exactly once for each item in the input 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 size of the input list.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input list gets bigger.
[X] Wrong: "Returning a value makes the function run slower by a lot."
[OK] Correct: Returning a single value at the end is very fast and does not add extra loops or big work.
Understanding how return values fit into time complexity helps you explain your code clearly and confidently in interviews.
"What if the function returned a list of all partial sums instead of a single total? How would the time complexity change?"