0
0
Typescriptprogramming~5 mins

Reverse mapping in numeric enums in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Reverse mapping in numeric enums
O(1)
Understanding Time Complexity

We want to understand how the time it takes to find values in a numeric enum changes as the enum grows.

Specifically, how does looking up a name by its numeric value behave as 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 uses a numeric enum and looks up the name of a color by its numeric value.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Direct property access on an object (reverse mapping) without loops.
  • How many times: Exactly once per lookup, no repeated traversal.
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 stays the same even if the enum grows larger.

Final Time Complexity

Time Complexity: O(1)

This means the lookup time stays constant no matter how many enum members exist.

Common Mistake

[X] Wrong: "Looking up a name by value in a numeric enum takes longer as the enum grows because it searches through all entries."

[OK] Correct: The enum is compiled into an object with direct keys, so the lookup is a simple direct access, not a search.

Interview Connect

Understanding how enum reverse mapping works helps you explain efficient lookups in TypeScript, showing you know how language features behave under the hood.

Self-Check

"What if the enum used string values instead of numbers? How would the time complexity of reverse lookup change?"