0
0
Swiftprogramming~5 mins

For-in loop with ranges in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: For-in loop with ranges
O(n)
Understanding Time Complexity

When we use a for-in loop with ranges in Swift, we want to know how the time it takes to run changes as the range gets bigger.

We ask: How does the number of steps grow when the range increases?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


for i in 1...n {
    print(i)
}
    

This code prints numbers from 1 up to n using a for-in loop with a range.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop runs once for each number from 1 to n.
  • How many times: Exactly n times, where n is the size of the range.
How Execution Grows With Input

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

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: The number of steps grows directly with n; if n doubles, steps double too.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the size of the range.

Common Mistake

[X] Wrong: "The loop runs in constant time because it just prints numbers."

[OK] Correct: Even though printing is simple, the loop runs once for each number, so time grows with n.

Interview Connect

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

Self-Check

"What if we changed the range to stride(from: 1, through: n, by: 2)? How would the time complexity change?"