0
0
Swiftprogramming~5 mins

Logical operators in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Logical operators
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
10Up to 10 checks
100Up to 100 checks
1000Up to 1000 checks

Pattern observation: The number of checks grows roughly in direct proportion to input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows linearly with the number of items to check.

Common Mistake

[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.

Interview Connect

Understanding how logical operators affect loops helps you explain code efficiency clearly and confidently.

Self-Check

"What if the function someOtherCheck() took longer time to run? How would the time complexity change?"