0
0
Typescriptprogramming~5 mins

String enums in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String enums
O(n)
Understanding Time Complexity

We want to understand how the time it takes to use string enums changes as we work with more enum values.

How does the program's work grow when we look up or compare enum values?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    enum Colors {
      Red = "RED",
      Green = "GREEN",
      Blue = "BLUE"
    }

    function isPrimaryColor(color: string): boolean {
      return color === Colors.Red || color === Colors.Green || color === Colors.Blue;
    }
    

This code checks if a given string matches one of the string enum values.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Comparing the input string to each enum value.
  • How many times: Once for each enum member (3 times here).
How Execution Grows With Input

Each time we add a new enum value, the function compares the input to one more string.

Input Size (n)Approx. Operations
33 comparisons
1010 comparisons
100100 comparisons

Pattern observation: The number of comparisons grows directly with the number of enum values.

Final Time Complexity

Time Complexity: O(n)

This means the time to check grows in a straight line as the number of enum values grows.

Common Mistake

[X] Wrong: "Checking a string enum value is always instant no matter how many values there are."

[OK] Correct: Each check compares the input to every enum value one by one, so more values mean more work.

Interview Connect

Understanding how operations grow with input size helps you explain your code's efficiency clearly and confidently.

Self-Check

"What if we stored enum values in a Set and checked membership instead? How would the time complexity change?"