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?
Practice
when expression in Kotlin do when used with ranges like in 1..5?Solution
Step 1: Understand the
The syntaxwhenwith range syntaxin 1..5insidewhenchecks if the value is between 1 and 5 inclusive.Step 2: Interpret the check
If the value is inside the range, the corresponding branch executes; otherwise, it moves to the next case.Final Answer:
It checks if the value falls within the specified range. -> Option DQuick Check:
whenwithinchecks range membership [OK]
in means inside the range [OK]- Thinking
increates a range instead of checking membership - Confusing
inwith assignment - Assuming it throws errors for out-of-range values
x is NOT in the range 10 to 20 using when in Kotlin?Solution
Step 1: Recall the correct negation syntax in
In Kotlin,when!inis used to check if a value is NOT in a range.Step 2: Match the syntax with options
when(x) { !in 10..20 -> "Outside" } uses!in 10..20correctly insidewhen. Other options use invalid keywords or syntax.Final Answer:
when(x) { !in 10..20 -> "Outside" } -> Option AQuick Check:
Use!into check exclusion from range [OK]
!in to say NOT in range [OK]- Using 'not in' instead of '!in'
- Writing variable name inside
whencase - Using undefined keywords like 'outside'
val x: Any = 42
val result = when (x) {
is Int -> "Integer"
in 1..10 -> "Small number"
else -> "Unknown"
}
println(result)Solution
Step 1: Check the type of
Variablexxis of typeAnybut holds the value 42, which is anInt.Step 2: Evaluate
The first branch checkswhenbranches in orderis Int, which is true, so it returns "Integer". The second branch is not checked because the first matched.Final Answer:
Integer -> Option CQuick Check:
whenmatches first true branch [OK]
is come before range checks [OK]- Assuming range check runs before type check
- Confusing value 42 as outside 1..10
- Thinking
whenchecks all branches
when expression:val y: Any = "Hello"
val output = when (y) {
in 1..5 -> "Number"
is String -> "Text"
else -> "Other"
}
println(output)Solution
Step 1: Analyze the
The variablein 1..5check onAnyyis of typeAny. Theinoperator with ranges requires a comparable type likeInt. Usingin 1..5onAnycauses a type mismatch error.Step 2: Check order of branches and syntax
Theis Stringcheck is valid but unreachable if the first branch errors. Also,whenin Kotlin does not requirebreak.Final Answer:
Cannot useinwithAnytype without casting -> Option AQuick Check:
Range checks need compatible types [OK]
in with ranges [OK]- Ignoring type mismatch for
inoperator - Thinking
whenneedsbreak - Assuming order of branches causes error
when expression that returns:- "Small Int" if the value is an
Int between 1 and 10 inclusive,- "Large Int" if the value is an
Int greater than 10,- "String" if the value is a
String,- "Other" for anything else.
Which of the following
when expressions correctly implements this?Solution
Step 1: Understand the conditions needed
We need to check ifvis anIntand then check its value range for "Small Int" or "Large Int". Also check ifvis aString.Step 2: Analyze each option's correctness
when (v) { in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" } incorrectly usesin 1..10without checking type first, causing errors ifvis notInt. when (v) { is Int in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" } uses invalid syntaxis Int in 1..10. when (v) { is Int && v in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" } uses invalid syntaxis Int && v in 1..10insidewhen. when (v) { is Int -> if (v in 1..10) "Small Int" else "Large Int" is String -> "String" else -> "Other" } correctly checks type first, then uses anifinside the branch to distinguish ranges.Final Answer:
Option B correctly implements the logic. -> Option BQuick Check:
Use nestedifinsidewhenfor complex conditions [OK]
- Using invalid syntax combining
isandin - Not checking type before range
- Trying to use logical operators directly in
whencases
Ready to prove it?
Pass the test and this pattern moves unknown
