0
0
Javascriptprogramming~5 mins

Do–while loop in Javascript - Time & Space Complexity

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

We want to understand how the time it takes to run a do-while loop changes as the input size grows.

Specifically, how many times the loop runs affects the total work done.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


let i = 0;
do {
  console.log(i);
  i++;
} while (i < n);
    

This code prints numbers from 0 up to n-1 using a do-while loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The do-while loop runs the block inside repeatedly.
  • How many times: It runs exactly n times, once for each number from 0 to n-1.
How Execution Grows With Input

As n grows, the number of times the loop runs grows directly with n.

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: The work grows in a straight line with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the loop grows directly in proportion to the input size n.

Common Mistake

[X] Wrong: "The do-while loop always runs at least once, so its time is constant regardless of n."

[OK] Correct: While the loop runs at least once, the total number of runs depends on n, so time grows with n.

Interview Connect

Understanding how loops like do-while scale helps you explain how your code handles bigger inputs clearly and confidently.

Self-Check

"What if the loop condition was based on a fixed number instead of n? How would the time complexity change?"