0
0
Kotlinprogramming~5 mins

When as expression returning value in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: When as expression returning value
O(n)
Understanding Time Complexity

We want to understand how the time taken by a Kotlin when expression changes as the input changes.

Specifically, how does the number of checks grow when using when to return a value?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun getDayType(day: Int): String = when(day) {
    1 -> "Monday"
    2 -> "Tuesday"
    3 -> "Wednesday"
    4 -> "Thursday"
    5 -> "Friday"
    6 -> "Saturday"
    7 -> "Sunday"
    else -> "Invalid day"
}
    

This code returns the name of the day for a given number using when as an expression.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking each case in the when expression.
  • How many times: Up to 7 checks in the worst case before matching or hitting else.
How Execution Grows With Input

As the input number changes, the when expression checks cases one by one until it finds a match.

Input Size (n)Approx. Operations
33 checks
55 checks
77 checks

Pattern observation: The number of checks grows linearly with the number of cases.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the matching case grows in a straight line as the number of cases increases.

Common Mistake

[X] Wrong: "The when expression always runs in constant time no matter how many cases it has."

[OK] Correct: Actually, the when expression checks cases one by one until it finds a match, so more cases mean more checks and longer time.

Interview Connect

Understanding how when expressions scale helps you explain how your code behaves with more conditions, showing you think about efficiency clearly.

Self-Check

"What if we replaced the when expression with a map lookup? How would the time complexity change?"