Else–if ladder in C++ - Time & Space Complexity
We want to understand how the time taken by an else-if ladder changes as the input changes.
Specifically, we ask: How many steps does the program take before it finds the right condition?
Analyze the time complexity of the following code snippet.
int checkNumber(int n) {
if (n == 1) {
return 10;
} else if (n == 2) {
return 20;
} else if (n == 3) {
return 30;
} else {
return 40;
}
}
This code checks the value of n and returns a number based on which condition matches first.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking conditions one by one in the else-if ladder.
- How many times: Up to the number of conditions until a match is found.
As the input number changes, the program checks conditions from top to bottom until it finds a match.
| Input Value (n) | Approx. Operations (condition checks) |
|---|---|
| 1 | 1 check |
| 2 | 2 checks |
| 3 | 3 checks |
| 4 | 4 checks (all conditions checked) |
Pattern observation: The number of checks grows linearly with the position of the matching condition.
Time Complexity: O(n)
This means the time grows linearly with the number of conditions checked before finding a match.
[X] Wrong: "The else-if ladder always takes the same time regardless of input."
[OK] Correct: The program stops checking as soon as it finds a match, so time depends on where the match is.
Understanding how condition checks add up helps you explain efficiency clearly and shows you can think about code beyond just making it work.
"What if we replaced the else-if ladder with a switch statement? How would the time complexity change?"