0
0
Kotlinprogramming~5 mins

When with ranges and types in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: When with ranges and types
O(1)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The when expression 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.
How Execution Grows With Input

Each check is simple and does not depend on input size. The number of checks is fixed (4 conditions).

Input Size (n)Approx. Operations
104 checks max
1004 checks max
10004 checks max

Pattern observation: The number of operations stays the same no matter how big the input value is.

Final Time Complexity

Time Complexity: O(1)

This means the time to check the value does not grow as the input changes; it stays constant.

Common Mistake

[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.

Interview Connect

Understanding how when works with ranges and types helps you explain how your code runs efficiently and predictably, a skill valued in real projects.

Self-Check

What if we added 100 more range checks inside the when? How would the time complexity change?