While loop in Javascript - Time & Space Complexity
We want to understand how the time a while loop takes changes as the input grows.
How does the number of steps grow when the loop runs more times?
Analyze the time complexity of the following code snippet.
let i = 0;
while (i < n) {
console.log(i);
i++;
}
This code prints numbers from 0 up to n-1 using a while loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs and prints a number each time.
- How many times: It repeats exactly n times, increasing i by 1 each time.
Each time n grows, the loop runs more times, directly matching n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The number of steps grows evenly as n grows.
Time Complexity: O(n)
This means the time grows in a straight line with the input size.
[X] Wrong: "The while loop always takes the same time no matter what."
[OK] Correct: The loop runs more times when n is bigger, so it takes longer.
Understanding how loops grow with input helps you explain your code clearly and shows you know how to write efficient programs.
"What if we increased i by 2 each time instead of 1? How would the time complexity change?"