Logical operators in Rust - Time & Space Complexity
Logical operators combine true/false values to make decisions in code.
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.
fn check_values(a: bool, b: bool, c: bool) -> bool {
a && b || c
}
fn main() {
let result = check_values(true, false, true);
println!("{}", result);
}
This code uses logical AND and OR to combine three true/false values and returns the result.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Evaluating a few logical operators on fixed inputs.
- How many times: Each operator runs once per function call; no loops or repeated steps.
Since the number of logical checks is fixed, the time does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | 3 logical checks |
| 10 | 3 logical checks |
| 100 | 3 logical 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 the code stays constant, no matter the input size.
[X] Wrong: "Logical operators take longer as inputs grow because they combine values."
[OK] Correct: Logical operators here only check a fixed number of values, so time does not increase with input size.
Understanding that simple logical checks run in constant time helps you explain code efficiency clearly and confidently.
"What if we changed the function to check logical operators on an array of booleans instead of just three values? How would the time complexity change?"