Switch statement - Time & Space Complexity
We want to see how the time to run a switch statement changes as the input changes.
Does it take longer if there are more cases or if the input is different?
Analyze the time complexity of the following code snippet.
int example(int x) {
switch (x) {
case 1:
return 10;
case 2:
return 20;
case 3:
return 30;
default:
return 0;
}
}
This code returns a value based on the input number using a switch statement.
Look for repeated work inside the switch.
- Primary operation: The switch checks the input once to find the matching case.
- How many times: Exactly one time per function call, no loops or repeated checks.
The switch picks the right case quickly without repeating work.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 1 check |
| 10 | 1 check |
| 100 | 1 check |
Pattern observation: The number of operations stays about the same no matter the input size.
Time Complexity: O(1)
This means the time to run the switch does not grow with input size; it stays constant.
[X] Wrong: "A switch statement checks every case one by one, so it takes longer with more cases."
[OK] Correct: Modern compilers often optimize switches to jump directly to the matching case, so it does not check all cases one by one.
Understanding how switch statements work helps you explain code efficiency clearly and shows you know how simple decisions affect performance.
"What if the switch had many cases but no breaks, causing fall-through? How would the time complexity change?"