0
0
Swiftprogramming~5 mins

Repeat-while loop in Swift - Time & Space Complexity

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

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

Specifically, how many times the loop runs depending on the input size.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


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

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

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The repeat-while loop runs the print and increment steps.
  • How many times: It runs once for each number from 0 up to n-1, so n times.
How Execution Grows With Input

As n grows, the loop runs more times, directly matching n.

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: The number of operations grows in a straight line with input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the loop grows directly with the size of n.

Common Mistake

[X] Wrong: "The repeat-while loop runs only once because it always runs at least once."

[OK] Correct: The loop runs once at minimum, but then keeps running until the condition is false, so it can run many times depending on n.

Interview Connect

Understanding how loops grow with input size helps you explain your code clearly and shows you can think about efficiency.

Self-Check

"What if we changed the loop to stop when count <= limit instead of count < limit? How would the time complexity change?"