0
0
Swiftprogramming~5 mins

Bool type and logical operators in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Bool type and logical operators
O(n)
Understanding Time Complexity

When using Bool values and logical operators, it is important to see how the number of operations changes as we combine more conditions.

We want to know how the time to evaluate these expressions grows when we add more logical checks.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func checkAllTrue(values: [Bool]) -> Bool {
    for value in values {
        if !value {
            return false
        }
    }
    return true
}

This function checks if all Boolean values in an array are true by scanning each one until it finds a false.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each Boolean in the array.
  • How many times: Up to once per element, stopping early if a false is found.
How Execution Grows With Input

As the number of Booleans increases, the function may check more values, but it can stop early if a false appears.

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 the number of values, but can be less if a false is found early.

Final Time Complexity

Time Complexity: O(n)

This means the time to check all values grows linearly with the number of Booleans in the array.

Common Mistake

[X] Wrong: "Logical operators always take constant time regardless of input size."

[OK] Correct: When used in a loop over many values, the total time depends on how many values are checked, so it grows with input size.

Interview Connect

Understanding how logical checks scale helps you write efficient conditions and shows you can think about how code runs as data grows.

Self-Check

What if we changed the function to check if any value is true instead of all? How would the time complexity change?