0
0
Swiftprogramming~5 mins

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

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

When we use a for-in loop to go through a collection, we want to know how the time it takes changes as the collection grows.

We ask: How does the work increase when the list gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


let numbers = [1, 2, 3, 4, 5]
var sum = 0
for number in numbers {
    sum += number
}
print(sum)
    

This code adds up all the numbers in a list using a for-in loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding each number to the sum inside the for-in loop.
  • How many times: Once for every item in the list.
How Execution Grows With Input

As the list gets bigger, the loop runs more times, doing more additions.

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

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the list size.

Common Mistake

[X] Wrong: "The loop runs faster because it just adds numbers quickly."

[OK] Correct: Even simple steps add up, so more items always mean more work.

Interview Connect

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

Self-Check

"What if we nested another for-in loop inside this one to compare each number with every other number? How would the time complexity change?"