Nested conditions in Rust - Time & Space Complexity
We want to see how the time a program takes changes when it uses nested conditions.
Specifically, we ask: does adding more layers of if-else checks make the program slower as input grows?
Analyze the time complexity of the following code snippet.
fn check_number(n: i32) -> &'static str {
if n > 0 {
if n % 2 == 0 {
"Positive even"
} else {
"Positive odd"
}
} else if n < 0 {
"Negative"
} else {
"Zero"
}
}
This code checks if a number is positive even, positive odd, negative, or zero using nested if-else conditions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single number check with nested if-else conditions.
- How many times: Each check runs once per function call; no loops or repeated traversals.
The time to check a number does not grow with the size or value of the number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 checks |
| 100 | 3 checks |
| 1000 | 3 checks |
Pattern observation: The number of steps stays the same no matter how big the input is.
Time Complexity: O(1)
This means the time to run the code stays constant regardless of input size.
[X] Wrong: "More nested ifs always make the program slower as input grows."
[OK] Correct: Nested conditions just add fixed checks; they don't repeat or grow with input size.
Understanding that nested conditions don't increase time with input size helps you explain code efficiency clearly and confidently.
"What if we added a loop that calls this nested condition check for each item in a list? How would the time complexity change?"