0
0
Swiftprogramming~5 mins

Break and continue behavior in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Break and continue behavior
O(1)
Understanding Time Complexity

When we use break or continue in loops, it changes how many times the loop runs. This affects how long the code takes to finish.

We want to see how these commands change the work done as the input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


var sum = 0
for i in 1...n {
    if i == 5 {
        break
    }
    if i % 2 == 0 {
        continue
    }
    sum += i
}

This code loops from 1 to n, but stops early if i reaches 5, and skips adding even numbers.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop running from 1 to n.
  • How many times: The loop stops early at i = 5 due to break, so it runs at most 5 times.
How Execution Grows With Input

Because the loop stops at 5, the number of steps does not grow with n after a point.

Input Size (n)Approx. Operations
105
1005
10005

Pattern observation: The work stays the same even if n gets bigger because of the break.

Final Time Complexity

Time Complexity: O(1)

This means the loop runs a fixed number of times, no matter how big the input is.

Common Mistake

[X] Wrong: "The loop always runs n times, so time is O(n)."

[OK] Correct: Because the break stops the loop early, it only runs a few times, not all n times.

Interview Connect

Understanding how break and continue affect loops helps you explain code efficiency clearly and shows you can think about real code behavior.

Self-Check

"What if we removed the break statement? How would the time complexity change?"