Switch statement in Go - Time & Space Complexity
We want to understand how the time it takes to run a switch statement changes as the input changes.
Specifically, we ask: does the number of cases affect how long the switch takes?
Analyze the time complexity of the following code snippet.
func checkNumber(n int) string {
switch n {
case 1:
return "One"
case 2:
return "Two"
case 3:
return "Three"
default:
return "Other"
}
}
This code checks a number and returns a word based on which case matches.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The switch compares the input value to each case until it finds a match.
- How many times: At most, it checks each case once in order until a match is found.
As the number of cases grows, the switch may need to check more cases before finding a match.
| Number of Cases (n) | Approx. Checks |
|---|---|
| 3 | Up to 3 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The checks grow roughly in direct proportion to the number of cases.
Time Complexity: O(n)
This means the time to find the matching case grows linearly with the number of cases.
[X] Wrong: "A switch statement always runs in constant time no matter how many cases it has."
[OK] Correct: The switch checks cases one by one until it finds a match, so more cases can mean more checks and longer time.
Understanding how switch statements scale helps you explain code efficiency clearly and shows you think about how programs behave as they grow.
"What if the switch used a map lookup instead of cases? How would the time complexity change?"