0
0
Kotlinprogramming~5 mins

Enum with when exhaustive check in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Enum with when exhaustive check
O(1)
Understanding Time Complexity

We want to understand how the time needed to run code changes when using an enum with a when statement that covers all cases.

How does the number of enum values affect how long the code takes to run?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


enum class Direction { NORTH, SOUTH, EAST, WEST }

fun describeDirection(dir: Direction): String = when(dir) {
    Direction.NORTH -> "Going north"
    Direction.SOUTH -> "Going south"
    Direction.EAST -> "Going east"
    Direction.WEST -> "Going west"
}
    

This code returns a description string for each direction using an exhaustive when statement on an enum.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking the enum value once in the when statement.
  • How many times: Exactly once per function call, no loops or recursion.
How Execution Grows With Input

The function checks the input enum value once and returns the matching string.

Input Size (number of enum values)Approx. Operations
41 check per call
101 check per call
1001 check per call

Pattern observation: The time to run does not grow with the number of enum values because the when statement directly matches the input.

Final Time Complexity

Time Complexity: O(1)

This means the function takes the same amount of time no matter how many enum values there are.

Common Mistake

[X] Wrong: "The time grows with the number of enum values because the when checks each case one by one."

[OK] Correct: The Kotlin compiler optimizes the when on enums to a fast lookup, so it does not check each case one by one at runtime.

Interview Connect

Understanding how enum and when statements work helps you write clear and efficient code, a skill valued in many coding tasks and interviews.

Self-Check

"What if we replaced the enum with a list of strings and used when to check each string? How would the time complexity change?"