0
0
Goprogramming~5 mins

Array initialization in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Array initialization
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop that sets each element in the slice.
  • How many times: Exactly n times, once for each element.
How Execution Grows With Input

As the slice size grows, the number of steps grows in the same way.

Input Size (n)Approx. Operations
1010 assignments
100100 assignments
10001000 assignments

Pattern observation: Doubling the slice size doubles the work needed.

Final Time Complexity

Time Complexity: O(n)

This means the time to fill the slice grows directly with its size.

Common Mistake

[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.

Interview Connect

Understanding how array initialization scales helps you explain performance clearly in interviews.

Self-Check

"What if we used a built-in function that sets all elements to zero instantly? How would the time complexity change?"