Index signatures for dynamic keys in Typescript - Time & Space Complexity
When using index signatures for dynamic keys, we want to know how the time to access or update data changes as the number of keys grows.
How does the program handle many dynamic keys efficiently?
Analyze the time complexity of the following code snippet.
interface Data {
[key: string]: number;
}
const data: Data = {};
function addEntry(key: string, value: number) {
data[key] = value;
}
function getEntry(key: string): number | undefined {
return data[key];
}
This code stores and retrieves numbers using dynamic string keys in an object.
- Primary operation: Accessing or setting a value by a dynamic key in an object.
- How many times: Each call accesses or sets one key directly without looping.
Each access or update looks up the key directly, so the time does not increase as more keys are added.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The operation time stays about the same no matter how many keys exist.
Time Complexity: O(1)
This means accessing or setting a value by a dynamic key takes the same short time regardless of how many keys are stored.
[X] Wrong: "Accessing a dynamic key gets slower as more keys are added because it searches through all keys."
[OK] Correct: Objects use a fast lookup method (like a hash table), so they find keys quickly without checking each one.
Understanding how dynamic keys work helps you explain how data structures handle many entries efficiently, a useful skill in many coding tasks.
"What if we used an array of key-value pairs instead of an object? How would the time complexity change?"