Logical operators in Swift - Time & Space Complexity
Logical operators combine true or false values to make decisions in code.
We want to see how the time to run code with logical operators changes as input grows.
Analyze the time complexity of the following code snippet.
func checkConditions(_ values: [Bool]) -> Bool {
for value in values {
if value && someOtherCheck() {
return true
}
}
return false
}
func someOtherCheck() -> Bool {
return true
}
This code checks each Boolean in an array and uses logical AND to decide if it should return true early.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of Booleans.
- How many times: Up to once per element, until a true condition is found.
As the array gets bigger, the loop may run more times, but it can stop early if condition is met.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows roughly in direct proportion to input size.
Time Complexity: O(n)
This means the time to run grows linearly with the number of items to check.
[X] Wrong: "Logical operators always make code run faster, so time complexity is constant."
[OK] Correct: Logical operators themselves are quick, but if used inside loops over many items, total time still grows with input size.
Understanding how logical operators affect loops helps you explain code efficiency clearly and confidently.
"What if the function someOtherCheck() took longer time to run? How would the time complexity change?"