Logical operators in C++ - Time & Space Complexity
Logical operators combine true or false values to make decisions in code.
We want to see how the time it takes to run code with logical operators changes as input grows.
Analyze the time complexity of the following code snippet.
bool checkAllTrue(const std::vector<bool>& flags) {
for (bool flag : flags) {
if (!flag) {
return false;
}
}
return true;
}
This code checks if all values in a list are true using logical NOT and a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the list.
- How many times: Up to once per element, stopping early if a false is found.
As the list gets bigger, the code checks more items, but may stop early if a false appears.
| 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 the list size.
Time Complexity: O(n)
This means the time to run grows linearly with the number of items to check.
[X] Wrong: "Logical operators make the code run instantly regardless of input size."
[OK] Correct: Logical operators themselves are simple, but when used inside loops, the total time depends on how many times the loop runs.
Understanding how logical checks inside loops affect time helps you explain code efficiency clearly and confidently.
"What if we changed the loop to check pairs of elements at once? How would the time complexity change?"