0
0
Swiftprogramming~5 mins

Range operators (... and ..<) in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Range operators (... and ..<)
O(n)
Understanding Time Complexity

When using Swift's range operators, it is important to know how the number of steps grows as the range size increases.

We want to understand how the time to process a range changes when the range gets bigger.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


let n = 100
for i in 0...n {
    print(i)
}

This code prints numbers from 0 up to n using the closed range operator (...).

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop runs once for each number in the range.
  • How many times: It runs n + 1 times because the range includes both 0 and n.
How Execution Grows With Input

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

Input Size (n)Approx. Operations
1011
100101
10001001

Pattern observation: The operations increase roughly one by one as n increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the loop grows in direct proportion to the size of the range.

Common Mistake

[X] Wrong: "The loop runs a fixed number of times no matter how big n is."

[OK] Correct: The loop runs once for each number in the range, so if n grows, the loop runs more times.

Interview Connect

Understanding how loops over ranges grow helps you explain how your code handles bigger inputs clearly and confidently.

Self-Check

"What if we changed the closed range operator (...) to the half-open range operator (..<)? How would the time complexity change?"