0
0
Typescriptprogramming~5 mins

Heterogeneous enums in Typescript - Time & Space Complexity

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

We want to understand how the time needed to use heterogeneous enums changes as the enum size grows.

Specifically, how does accessing or searching enum values behave when enums mix strings and numbers?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    enum MixedEnum {
      No = 0,
      Yes = 1,
      Maybe = 2,
      Later = "later"
    }

    function isValueInEnum(value: string | number): boolean {
      return Object.values(MixedEnum).includes(value);
    }
    

This code defines a heterogeneous enum with both numbers and strings, then checks if a value exists in it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The call to Object.values(MixedEnum) creates an array of enum values, then includes checks each element one by one.
  • How many times: The includes method may check up to all enum values, so it runs once per enum value.
How Execution Grows With Input

As the enum gets bigger, the number of checks grows directly with the number of enum values.

Input Size (n)Approx. Operations
10About 10 checks
100About 100 checks
1000About 1000 checks

Pattern observation: The time grows in a straight line with the number of enum values.

Final Time Complexity

Time Complexity: O(n)

This means the time to check a value grows directly with the number of enum entries.

Common Mistake

[X] Wrong: "Checking if a value is in an enum is always instant, no matter the size."

[OK] Correct: Because includes checks each value one by one, bigger enums take longer to search.

Interview Connect

Understanding how enum lookups scale helps you write efficient code and explain your reasoning clearly in interviews.

Self-Check

What if we stored enum values in a Set instead of an array? How would the time complexity change?