0
0
Kotlinprogramming~5 mins

When without argument in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: When without argument
O(n)
Understanding Time 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?

Scenario Under Consideration

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 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 checks conditions until one matches or all are checked.
How Execution Grows With Input

As you add more conditions, the program checks more cases in order until it finds a match.

Number of Conditions (n)Approx. Checks
3Up to 3 checks
10Up to 10 checks
100Up to 100 checks

Pattern observation: The number of checks grows directly with the number of conditions.

Final Time Complexity

Time Complexity: O(n)

This means the time to find a matching condition grows linearly as you add more conditions.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if the conditions were reordered so the most common case is first? How would the time complexity be affected in practice?"