Nested if statements in Java - Time & Space Complexity
We want to see how the time it takes to run nested if statements changes as the input grows.
Specifically, we ask: Does adding more conditions inside each other make the program slower?
Analyze the time complexity of the following code snippet.
int checkNumber(int n) {
if (n > 0) {
if (n % 2 == 0) {
return 1;
} else {
return 2;
}
} else {
return 0;
}
}
This code checks if a number is positive and then if it is even or odd.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: There are no loops or repeated steps here.
- How many times: Each condition is checked only once per call.
Since the code only checks conditions 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 steps stays the same no matter the input size.
Time Complexity: O(1)
This means the time to run the code stays constant, no matter how big the input is.
[X] Wrong: "Nested if statements always make the program slower as input grows."
[OK] Correct: Nested ifs just check conditions once each; they don't repeat work based on input size.
Understanding that nested ifs do not increase time with input size helps you explain code efficiency clearly and confidently.
"What if we added a loop inside the nested if statements? How would the time complexity change?"