When with multiple conditions in Kotlin - Time & Space Complexity
We want to see how the time it takes to run a Kotlin when statement changes as we add more conditions.
How does checking multiple conditions affect the program's speed?
Analyze the time complexity of the following code snippet.
fun checkNumber(num: Int): String {
return when (num) {
1, 2, 3 -> "Small number"
4, 5, 6 -> "Medium number"
7, 8, 9 -> "Large number"
else -> "Unknown"
}
}
This code checks a number against several groups of values using multiple conditions in each when branch.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking the input number against each condition group in the
whenstatement. - How many times: The program compares the input to each condition until it finds a match or reaches
else.
As the number of condition groups grows, the program checks more groups one by one until it finds a match.
| Input Size (number of condition groups) | Approx. Operations (checks) |
|---|---|
| 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 condition groups.
Time Complexity: O(n)
This means the time to find the matching condition grows in a straight line as you add more condition groups.
[X] Wrong: "The when statement checks all conditions at once, so time stays the same no matter how many conditions there are."
[OK] Correct: The when checks conditions one by one until it finds a match, so more conditions mean more checks in the worst case.
Understanding how multiple conditions affect time helps you explain code efficiency clearly and shows you can think about how programs grow with input size.
"What if we replaced the multiple conditions in each when branch with a data structure lookup? How would the time complexity change?"