Array initialization in Go - Time & Space Complexity
When we create an array and fill it with values, the computer does some work for each item.
We want to know how this work grows as the array gets bigger.
Analyze the time complexity of the following code snippet.
package main
func initializeArray(n int) []int {
arr := make([]int, n)
for i := 0; i < n; i++ {
arr[i] = i * 2
}
return arr
}
This code creates a slice of size n and fills each position with double its index.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop that sets each element in the slice. - How many times: Exactly
ntimes, once for each element.
As the slice size grows, the number of steps grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments |
| 100 | 100 assignments |
| 1000 | 1000 assignments |
Pattern observation: Doubling the slice size doubles the work needed.
Time Complexity: O(n)
This means the time to fill the slice grows directly with its size.
[X] Wrong: "Initializing an array is instant and does not depend on size."
[OK] Correct: Each element must be set, so bigger arrays take more time.
Understanding how array initialization scales helps you explain performance clearly in interviews.
"What if we used a built-in function that sets all elements to zero instantly? How would the time complexity change?"