0
0
Swiftprogramming~5 mins

For-in with where clause in Swift - Time & Space Complexity

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

We want to understand how the time it takes to run a loop with a condition changes as the input grows.

How does adding a filter inside a loop affect the total work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers where number % 2 == 0 {
    print(number)
}
    

This code loops through a list of numbers and prints only the even ones.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each element in the array.
  • How many times: Once for every item in the list, regardless of the condition.
How Execution Grows With Input

As the list gets bigger, the loop checks each item once, even if it only prints some.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The number of checks grows directly with the size of the list.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items.

Common Mistake

[X] Wrong: "Because we only print some items, the loop runs fewer times."

[OK] Correct: The loop still checks every item to decide if it should print, so it runs once per item.

Interview Connect

Understanding how conditions inside loops affect performance helps you write efficient code and explain your reasoning clearly.

Self-Check

"What if we replaced the 'where' clause with an 'if' statement inside the loop? How would the time complexity change?"