Logical operators - Time & Space Complexity
Logical operators combine conditions to decide true or false results.
We want to see how using these operators affects how long the program takes to run.
Analyze the time complexity of the following code snippet.
#include <stdio.h>
int check(int a, int b, int c) {
if ((a && b) || c) {
return 1;
}
return 0;
}
This code checks if certain conditions with logical AND and OR are true.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single evaluation of logical conditions.
- How many times: Once per function call, no loops or repeated checks inside.
Since the code only checks a few values once, the time does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 checks |
| 100 | 3 checks |
| 1000 | 3 checks |
Pattern observation: The number of operations stays the same no matter how big the input is.
Time Complexity: O(1)
This means the time to run does not change as input size changes; it stays constant.
[X] Wrong: "Logical operators make the program slower as input grows because they combine many conditions."
[OK] Correct: Logical operators here only check a fixed number of values once, so the time does not increase with input size.
Understanding how simple condition checks work helps you explain code efficiency clearly and confidently.
"What if the conditions were inside a loop running n times? How would the time complexity change?"