0
0
Kotlinprogramming~5 mins

Enum with properties and methods in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Enum with properties and methods
O(n)
Understanding Time Complexity

Enums with properties and methods let us group related values with extra details and actions.

We want to see how the time to run code with enums changes as we use more enum values or call their methods.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

enum class Color(val rgb: Int) {
    RED(0xFF0000) {
        override fun printName() = println("Red")
    },
    GREEN(0x00FF00) {
        override fun printName() = println("Green")
    },
    BLUE(0x0000FF) {
        override fun printName() = println("Blue")
    };

    abstract fun printName()
}

fun printAllColors() {
    for (color in Color.values()) {
        color.printName()
    }
}

This code defines an enum with three colors, each having a property and a method. Then it loops over all colors and calls their method.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping over all enum values with Color.values() and calling printName().
  • How many times: Once for each enum constant (3 times here, but can be more if enum grows).
How Execution Grows With Input

As the number of enum constants grows, the loop runs once per constant.

Input Size (n)Approx. Operations
33 calls to printName()
1010 calls to printName()
100100 calls to printName()

Pattern observation: The work grows directly with the number of enum values. More values mean more method calls.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the loop and call methods grows linearly with the number of enum constants.

Common Mistake

[X] Wrong: "Enums are fixed and small, so their methods always run in constant time no matter what."

[OK] Correct: While enums often have few values, if you loop over all values or add many constants, the time grows with the number of constants, not always constant.

Interview Connect

Understanding how enum methods run helps you explain how your code scales when using enums with many values or complex methods.

Self-Check

"What if the printName() method called another function that loops over a list inside each enum constant? How would the time complexity change?"