0
0
Typescriptprogramming~5 mins

Numeric enums in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Numeric enums
O(1)
Understanding Time Complexity

We want to understand how the time it takes to work with numeric enums changes as the number of enum members grows.

Specifically, how does accessing or searching enum values behave when the enum size increases?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    enum Colors {
      Red,    // 0
      Green,  // 1
      Blue    // 2
    }

    function getColorName(value: number): string | undefined {
      return Colors[value];
    }
    

This code defines a numeric enum and a function that looks up the name of a color by its numeric value.

Identify Repeating Operations
  • Primary operation: Direct lookup in an object (enum reverse mapping)
  • How many times: Single operation per lookup, no loops or recursion
How Execution Grows With Input

Looking up a value in the enum is like checking a label on a box directly, no matter how many boxes there are.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time to find a name does not grow with the number of enum members; it stays constant.

Final Time Complexity

Time Complexity: O(1)

This means looking up a numeric enum value takes the same amount of time no matter how many items are in the enum.

Common Mistake

[X] Wrong: "Looking up a numeric enum value takes longer as the enum gets bigger because it has to check each item."

[OK] Correct: Numeric enums in TypeScript create an object with direct keys, so the lookup is a quick direct access, not a search through all items.

Interview Connect

Understanding how enum lookups work helps you explain efficient data access in TypeScript, showing you know how language features impact performance.

Self-Check

"What if we changed the enum to a string enum? How would the time complexity of looking up a name by value change?"