0
0
Goprogramming~5 mins

For loop as while in Go - Time & Space Complexity

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

We want to see how the time it takes to run a for loop used like a while loop changes as the input grows.

How does the number of steps grow when the loop runs more times?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


package main

func countDown(n int) {
    for n > 0 {
        n--
    }
}

This code counts down from n to zero using a for loop that acts like a while loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop runs and decreases n by 1 each time.
  • How many times: The loop runs exactly n times until n reaches zero.
How Execution Grows With Input

Each time n gets bigger, the loop runs more times, directly matching n.

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: The number of steps grows in a straight line with n.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly with the size of n.

Common Mistake

[X] Wrong: "The loop runs a fixed number of times no matter what n is."

[OK] Correct: The loop depends on n and runs once for each count down, so bigger n means more steps.

Interview Connect

Understanding how loops grow with input helps you explain your code clearly and shows you know how programs scale.

Self-Check

"What if we changed the loop to decrease n by 2 each time? How would the time complexity change?"