0
0
Swiftprogramming~5 mins

Stride for custom step in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Stride for custom step
O(n / step)
Understanding Time Complexity

When using stride with a custom step in Swift, it is important to understand how the number of steps affects the time it takes to run the code.

We want to know how the execution time grows as the range and step size change.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


let start = 0
let end = 100
let step = 5

for i in stride(from: start, to: end, by: step) {
    print(i)
}
    

This code prints numbers from 0 up to but not including 100, stepping by 5 each time.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop using stride repeats printing.
  • How many times: It repeats once for each step from start to end, increasing by the step size.
How Execution Grows With Input

As the range between start and end grows, the number of loop steps increases proportionally to how many steps fit in that range.

Input Size (n)Approx. Operations
102 (steps of 5: 0, 5)
10020 (steps of 5: 0, 5, 10, ..., 95)
1000200 (steps of 5: 0, 5, 10, ..., 995)

Pattern observation: The number of operations grows roughly in direct proportion to the input size divided by the step size.

Final Time Complexity

Time Complexity: O(n / step)

This means the time grows linearly with the number of steps taken, which depends on the range size divided by the step size.

Common Mistake

[X] Wrong: "The loop always runs n times regardless of the step size."

[OK] Correct: The step size controls how many times the loop runs; bigger steps mean fewer iterations.

Interview Connect

Understanding how loops with custom steps scale helps you explain performance clearly and shows you can reason about code efficiency in real situations.

Self-Check

"What if we changed the step size to 1? How would the time complexity change?"