0
0
Kotlinprogramming~5 mins

When with multiple conditions in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: When with multiple conditions
O(n)
Understanding Time Complexity

We want to see how the time it takes to run a Kotlin when statement changes as we add more conditions.

How does checking multiple conditions affect the program's speed?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun checkNumber(num: Int): String {
    return when (num) {
        1, 2, 3 -> "Small number"
        4, 5, 6 -> "Medium number"
        7, 8, 9 -> "Large number"
        else -> "Unknown"
    }
}
    

This code checks a number against several groups of values using multiple conditions in each when branch.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking the input number against each condition group in the when statement.
  • How many times: The program compares the input to each condition until it finds a match or reaches else.
How Execution Grows With Input

As the number of condition groups grows, the program checks more groups one by one until it finds a match.

Input Size (number of condition groups)Approx. Operations (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 condition groups.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the matching condition grows in a straight line as you add more condition groups.

Common Mistake

[X] Wrong: "The when statement checks all conditions at once, so time stays the same no matter how many conditions there are."

[OK] Correct: The when checks conditions one by one until it finds a match, so more conditions mean more checks in the worst case.

Interview Connect

Understanding how multiple conditions affect time helps you explain code efficiency clearly and shows you can think about how programs grow with input size.

Self-Check

"What if we replaced the multiple conditions in each when branch with a data structure lookup? How would the time complexity change?"