For loop in PowerShell - Time & Space Complexity
We want to understand how the time a for loop takes changes as we increase the number of times it runs.
How does the work grow when the loop runs more times?
Analyze the time complexity of the following code snippet.
for ($i = 0; $i -lt $n; $i++) {
Write-Output "Number: $i"
}
This code prints numbers from 0 up to one less than n using a for loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs the Write-Output command.
- How many times: Exactly n times, once for each number from 0 to n-1.
Each time we increase n, the loop runs more times, so the total work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times |
| 100 | 100 times |
| 1000 | 1000 times |
Pattern observation: Doubling n doubles the work done by the loop.
Time Complexity: O(n)
This means the time grows in a straight line with the number of loop runs.
[X] Wrong: "The loop runs faster as n gets bigger because computers are fast."
[OK] Correct: Even though computers are fast, the loop still does more work when n is bigger, so it takes more time.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how to think about efficiency.
"What if we added a nested for loop inside this loop that also runs n times? How would the time complexity change?"