When with ranges and types in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run a Kotlin when expression changes as the input grows.
Specifically, how checking ranges and types inside when affects performance.
Analyze the time complexity of the following code snippet.
fun checkValue(x: Any) = when (x) {
in 1..10 -> "Small number"
in 11..100 -> "Medium number"
is String -> "A string"
else -> "Other"
}
This code checks if x falls in certain number ranges or is a string, then returns a message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
whenexpression checks each condition one by one. - How many times: It stops as soon as one condition matches, so in the worst case it checks all conditions once.
Each check is simple and does not depend on input size. The number of checks is fixed (4 conditions).
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 4 checks max |
| 100 | 4 checks max |
| 1000 | 4 checks max |
Pattern observation: The number of operations stays the same no matter how big the input value is.
Time Complexity: O(1)
This means the time to check the value does not grow as the input changes; it stays constant.
[X] Wrong: "Checking ranges inside when takes longer if the number is bigger."
[OK] Correct: The code only checks fixed ranges one by one, so the size of the number does not affect how many checks happen.
Understanding how when works with ranges and types helps you explain how your code runs efficiently and predictably, a skill valued in real projects.
What if we added 100 more range checks inside the when? How would the time complexity change?