0
0
Goprogramming~5 mins

For loop basics in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: For loop basics
O(n)
Understanding Time Complexity

When we use a for loop, the program repeats some steps many times. Understanding how this repetition grows helps us know how fast or slow the program runs.

We want to find out how the number of repeated steps changes as the loop runs more times.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


for i := 0; i < n; i++ {
    fmt.Println(i)
}
    

This code prints numbers from 0 up to n-1, repeating the print step n times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The print statement inside the for loop.
  • How many times: Exactly n times, once for each loop cycle.
How Execution Grows With Input

As n grows, the number of print steps grows the same way. If n doubles, the steps double too.

Input Size (n)Approx. Operations
1010 print steps
100100 print steps
10001000 print steps

Pattern observation: The work grows directly with n, so more input means more steps in a straight line.

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows in direct proportion to the number of times the loop runs.

Common Mistake

[X] Wrong: "The loop runs instantly no matter how big n is."

[OK] Correct: Each loop step takes some time, so more steps mean more total time. The program does not skip the repeated work.

Interview Connect

Knowing how loops affect time helps you explain your code clearly and shows you understand how programs grow with input size. This skill is useful in many coding situations.

Self-Check

"What if we added a nested loop inside this loop? How would the time complexity change?"