When without argument in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run a Kotlin when expression without an argument changes as we add more conditions.
How does the number of checks grow when we add more cases?
Analyze the time complexity of the following code snippet.
fun checkNumber(num: Int) {
when {
num < 0 -> println("Negative")
num == 0 -> println("Zero")
num > 0 -> println("Positive")
}
}
This code checks a number against several conditions without using a direct argument in when.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
whenexpression checks each condition one by one. - How many times: It checks conditions until one matches or all are checked.
As you add more conditions, the program checks more cases in order until it finds a match.
| Number of Conditions (n) | Approx. 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 conditions.
Time Complexity: O(n)
This means the time to find a matching condition grows linearly as you add more conditions.
[X] Wrong: "The when without argument checks all conditions at once, so it is constant time."
[OK] Correct: Actually, it checks conditions one by one until it finds a match, so more conditions mean more checks.
Understanding how when without argument works helps you reason about condition checks and efficiency in Kotlin code, a useful skill for clear and efficient programming.
"What if the conditions were reordered so the most common case is first? How would the time complexity be affected in practice?"