Nested conditional statements - Time & Space Complexity
We want to see how the time to run nested conditional statements changes as input changes.
Are these conditions making the program slower when inputs grow?
Analyze the time complexity of the following code snippet.
int checkValue(int x) {
if (x > 0) {
if (x % 2 == 0) {
return 1;
} else {
return 2;
}
} else {
return 3;
}
}
This code checks a number and returns different results based on nested conditions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single check of conditions (if-else statements)
- How many times: Exactly once per function call
The program only checks conditions once, no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2-3 checks |
| 100 | 2-3 checks |
| 1000 | 2-3 checks |
Pattern observation: The number of operations stays the same regardless of input size.
Time Complexity: O(1)
This means the time to run does not grow with input size; it stays constant.
[X] Wrong: "Nested ifs always make the program slower as input grows."
[OK] Correct: Nested conditions run only once per input, so they do not slow down with bigger inputs.
Understanding how conditions affect time helps you explain your code clearly and shows you know what really costs time in programs.
"What if we added a loop around these nested conditions? How would the time complexity change?"