Else–if ladder in Go - Time & Space Complexity
We want to see how the time taken by an else-if ladder changes as the input changes.
Specifically, how many checks happen when we run the code?
Analyze the time complexity of the following code snippet.
func checkNumber(n int) string {
if n == 1 {
return "One"
} else if n == 2 {
return "Two"
} else if n == 3 {
return "Three"
} else {
return "Other"
}
}
This code checks a number against several conditions one by one until it finds a match or reaches the last else.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking conditions one after another in the else-if ladder.
- How many times: Up to the number of conditions until a match is found or all are checked.
As the input number changes, the code checks conditions in order until it finds a match.
| Input Value (n) | Approx. Operations |
|---|---|
| 1 | 1 check (first condition matches) |
| 2 | 2 checks (first fails, second matches) |
| 4 | 3 checks (all conditions fail, last else runs) |
Pattern observation: The number of checks grows linearly with how far down the ladder the match is.
Time Complexity: O(n)
This means the time grows in a straight line with the number of conditions checked.
[X] Wrong: "Else-if ladder always runs in constant time because it just checks a few conditions."
[OK] Correct: The time depends on where the match is found; if it's near the end, many checks happen, so time grows with the number of conditions.
Understanding how else-if ladders scale helps you explain decision-making code clearly and shows you can think about efficiency in simple condition checks.
"What if we replaced the else-if ladder with a map lookup? How would the time complexity change?"