String enums in Typescript - Time & Space 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?
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 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).
Each time we add a new enum value, the function compares the input to one more string.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 comparisons |
| 10 | 10 comparisons |
| 100 | 100 comparisons |
Pattern observation: The number of comparisons grows directly with the number of enum values.
Time Complexity: O(n)
This means the time to check grows in a straight line as the number of enum values grows.
[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.
Understanding how operations grow with input size helps you explain your code's efficiency clearly and confidently.
"What if we stored enum values in a Set and checked membership instead? How would the time complexity change?"