Array declaration in Go - Time & Space Complexity
When we declare an array in Go, it is important to understand how this affects the program's speed as the array size changes.
We want to know how the time to create an array grows when the array gets bigger.
Analyze the time complexity of the following code snippet.
package main
func main() {
var numbers [100]int
for i := 0; i < len(numbers); i++ {
numbers[i] = i * 2
}
}
This code declares an array of 100 integers and fills it with values by looping through each position.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that assigns values to each element in the array.
- How many times: Exactly once for each element, so 100 times in this example.
As the array size grows, the number of assignments grows at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments |
| 100 | 100 assignments |
| 1000 | 1000 assignments |
Pattern observation: The work grows directly with the size of the array; doubling the array doubles the work.
Time Complexity: O(n)
This means the time to fill the array grows in a straight line with the number of elements.
[X] Wrong: "Declaring an array is instant and does not depend on its size."
[OK] Correct: While declaration reserves space quickly, initializing or filling the array requires time proportional to its size.
Understanding how array operations scale helps you explain your code choices clearly and shows you know how programs handle data efficiently.
"What if we replaced the array with a slice that grows dynamically? How would the time complexity change?"