0
0
PowerShellscripting~5 mins

While and Do-While loops in PowerShell - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: While and Do-While loops
O(n)
Understanding Time Complexity

We want to understand how the time a script takes grows when using while or do-while loops.

Specifically, how does the number of steps change as the loop runs more times?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


$count = 0
while ($count -lt 10) {
    Write-Output "Count is $count"
    $count++
}

This code prints numbers from 0 to 9 using a while loop that runs until the count reaches 10.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop runs repeatedly.
  • How many times: It runs once for each count from 0 up to 9, so 10 times.
How Execution Grows With Input

As the number of loop runs increases, the total steps increase in the same way.

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: The operations grow directly with the input size; doubling input doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the number of loop runs.

Common Mistake

[X] Wrong: "The loop runs instantly no matter how many times it repeats."

[OK] Correct: Each loop run takes time, so more runs mean more total time.

Interview Connect

Understanding how loops affect time helps you explain your code clearly and shows you know how scripts scale.

Self-Check

"What if we changed the loop to run until count is less than n squared? How would the time complexity change?"