0
0
Swiftprogramming~5 mins

Comparison operators in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Comparison operators
O(n)
Understanding Time Complexity

When we use comparison operators, we want to know how long it takes to compare values as the input grows.

We ask: How does the time to compare change when we have more items?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


let numbers = [3, 7, 2, 9, 5]
let target = 7
var found = false

for number in numbers {
    if number == target {
        found = true
        break
    }
}

This code checks if a target number is in the list by comparing each item until it finds a match.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Comparing each number to the target using ==.
  • How many times: Up to once for each item in the list, until a match is found.
How Execution Grows With Input

As the list gets bigger, the number of comparisons can grow up to the size of the list.

Input Size (n)Approx. Operations
10Up to 10 comparisons
100Up to 100 comparisons
1000Up to 1000 comparisons

Pattern observation: The number of comparisons grows roughly in a straight line with the list size.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the target grows directly with the number of items you check.

Common Mistake

[X] Wrong: "Comparing two values takes longer as the list grows."

[OK] Correct: Each comparison between two values takes the same small amount of time, no matter the list size. The total time grows because you do more comparisons, not because each one is slower.

Interview Connect

Understanding how comparison operations add up helps you explain how searching or filtering works in real code. It shows you can think about efficiency clearly.

Self-Check

"What if we used a sorted list and stopped searching early? How would the time complexity change?"