Else–if ladder in Java - Time & Space Complexity
We want to understand how the time taken by an else-if ladder changes as the input changes.
Specifically, how many checks happen before the program finds the right condition?
Analyze the time complexity of the following code snippet.
int number = 15;
if (number < 10) {
System.out.println("Less than 10");
} else if (number < 20) {
System.out.println("Between 10 and 19");
} else if (number < 30) {
System.out.println("Between 20 and 29");
} else {
System.out.println("30 or more");
}
This code checks a number against several conditions one by one until one matches.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sequential condition checks in the else-if ladder.
- How many times: Up to the number of conditions until one matches.
As the input number changes, the program checks conditions one by one until it finds a match.
| Input Size (number of conditions) | Approx. Operations (checks) |
|---|---|
| 3 | Up to 3 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows linearly with the number of conditions.
Time Complexity: O(n)
This means the time grows in a straight line with the number of conditions checked.
[X] Wrong: "The else-if ladder checks all conditions every time."
[OK] Correct: The program stops checking as soon as one condition is true, so it does not always check all conditions.
Understanding how else-if ladders work helps you explain decision-making in code clearly and shows you can analyze simple control flows efficiently.
"What if we replaced the else-if ladder with separate if statements? How would the time complexity change?"