Comparison operators in Swift - Time & Space 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?
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 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.
As the list gets bigger, the number of comparisons can grow up to the size of the list.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 comparisons |
| 100 | Up to 100 comparisons |
| 1000 | Up to 1000 comparisons |
Pattern observation: The number of comparisons grows roughly in a straight line with the list size.
Time Complexity: O(n)
This means the time to find the target grows directly with the number of items you check.
[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.
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.
"What if we used a sorted list and stopped searching early? How would the time complexity change?"