0
0
Typescriptprogramming~5 mins

Index signatures for dynamic keys in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Index signatures for dynamic keys
O(1)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

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
101
1001
10001

Pattern observation: The operation time stays about the same no matter how many keys exist.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how dynamic keys work helps you explain how data structures handle many entries efficiently, a useful skill in many coding tasks.

Self-Check

"What if we used an array of key-value pairs instead of an object? How would the time complexity change?"