Reverse mapping in numeric enums in Typescript - Time & Space 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?
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 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.
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 |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time to find a name stays the same even if the enum grows larger.
Time Complexity: O(1)
This means the lookup time stays constant no matter how many enum members exist.
[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.
Understanding how enum reverse mapping works helps you explain efficient lookups in TypeScript, showing you know how language features behave under the hood.
"What if the enum used string values instead of numbers? How would the time complexity of reverse lookup change?"