Function parameters in Go - Time & Space Complexity
When we use function parameters, we want to know how the time to run the function changes as the input changes.
We ask: How does the size or number of parameters affect the work the function does?
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 the numbers given in a list and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for every number 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 number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of input items.
[X] Wrong: "Function parameters do not affect time because they are just inputs."
[OK] Correct: The size or amount of data passed as parameters can change how many steps the function takes, so it does affect time.
Understanding how input size affects function time helps you explain your code clearly and shows you think about efficiency, a skill valued in real projects.
"What if the function took two lists instead of one? How would the time complexity change?"