0
0
Swiftprogramming~5 mins

While loop in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: While loop
O(n)
Understanding Time Complexity

We want to understand how the time a while loop takes changes as the input grows.

Specifically, how many times does the loop run when the input gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


var count = 0
let n = 100
while count < n {
    print(count)
    count += 1
}
    

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

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 number from 0 to n-1, so n times.
How Execution Grows With Input

As n grows, the number of times the loop runs grows the same way.

Input Size (n)Approx. Operations
10About 10 times
100About 100 times
1000About 1000 times

Pattern observation: The operations increase directly with n; if n doubles, operations double.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the input size.

Common Mistake

[X] Wrong: "The while loop runs a fixed number of times no matter the input."

[OK] Correct: The loop runs as many times as n, so bigger n means more runs.

Interview Connect

Understanding how loops grow with input size helps you explain your code clearly and shows you know how to write efficient programs.

Self-Check

"What if we changed the loop to count down from n to 0? How would the time complexity change?"