Switch with compound cases in Swift - Time & Space Complexity
Let's see how the time it takes to run a switch statement with multiple cases changes as we add more cases.
We want to know how the program's work grows when checking several options in a switch.
Analyze the time complexity of the following code snippet.
let value = 3
switch value {
case 1, 2:
print("One or Two")
case 3, 4, 5:
print("Three to Five")
default:
print("Other")
}
This code checks the value against groups of numbers using compound cases in a switch statement.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The switch statement checks each case group one by one.
- How many times: It compares the value to each case group until it finds a match or reaches default.
As the number of case groups grows, the program checks more groups before finding a match.
| Input Size (number of case groups) | Approx. Operations (comparisons) |
|---|---|
| 3 | Up to 3 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows directly with the number of case groups.
Time Complexity: O(n)
This means the time to find a matching case grows in a straight line as you add more case groups.
[X] Wrong: "Switch statements always run in constant time no matter how many cases there are."
[OK] Correct: Actually, the switch checks cases one by one until it finds a match, so more cases mean more checks and longer time.
Understanding how switch statements work helps you explain how your code handles many options efficiently and shows you think about performance clearly.
"What if we replaced the switch with a dictionary lookup? How would the time complexity change?"