Pointer behavior in functions in Go - Time & Space Complexity
When we use pointers in functions, it changes how data is accessed and changed.
We want to see how this affects the time it takes for the program to run as input grows.
Analyze the time complexity of the following code snippet.
package main
func incrementAll(nums *[]int) {
for i := range *nums {
(*nums)[i]++
}
}
func main() {
numbers := []int{1, 2, 3, 4, 5}
incrementAll(&numbers)
}
This code increases each number in a list by 1 using a pointer to modify the original list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the list.
- How many times: Once for every item in the list.
As the list gets bigger, the loop runs more times, directly matching the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The work grows evenly as the list grows; doubling the list doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of the list.
[X] Wrong: "Using pointers makes the function run faster because it avoids copying data."
[OK] Correct: While pointers avoid copying, the loop still visits every item, so time depends on list size, not pointer use.
Understanding how pointers affect function behavior and time helps you explain your code clearly and shows you know how data flows in programs.
"What if the function used a copy of the list instead of a pointer? How would the time complexity change?"