Why Hash Map Exists and What Problem It Solves in DSA Typescript - Performance Analysis
We want to understand why hash maps are useful by looking at how fast they let us find things.
The question is: How does using a hash map change the time it takes to find or store data?
Analyze the time complexity of the following code snippet.
// Simple search in an array
function findValue(arr: number[], target: number): boolean {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return true;
}
}
return false;
}
// Using a hash map for quick lookup
function findValueWithMap(map: Map, target: number): boolean {
return map.has(target);
}
This code shows two ways to check if a value exists: searching an array and using a hash map.
- Primary operation: Checking each item in the array one by one.
- How many times: Up to n times, where n is the number of items in the array.
- Hash map operation: Directly checking if the key exists without looping.
- How many times: Just once, no matter how big the map is.
As the list gets bigger, searching each item takes longer, but hash map lookup stays fast.
| Input Size (n) | Array Search Operations | Hash Map Lookup Operations |
|---|---|---|
| 10 | Up to 10 checks | 1 check |
| 100 | Up to 100 checks | 1 check |
| 1000 | Up to 1000 checks | 1 check |
Pattern observation: Array search grows linearly with input size, hash map lookup stays constant.
Time Complexity: O(n) for array search, O(1) average for hash map lookup
This means searching an array takes longer as it grows, but hash maps let us find things quickly no matter the size.
[X] Wrong: "Hash maps always find items instantly without any cost."
[OK] Correct: Hash maps usually find items quickly, but sometimes collisions happen, making lookup slower. Still, on average, they are much faster than searching arrays.
Understanding why hash maps exist helps you explain how to choose the right tool for fast data lookup, a key skill in many coding problems.
"What if the array was sorted? How would the time complexity change if we used binary search instead of linear search?"
Practice
Hash Map instead of a simple list to store key-value pairs?Solution
Step 1: Understand the problem with lists
Lists require checking each item one by one to find a value by key, which is slow for large data.Step 2: How hash maps solve this
Hash maps use a special function to find the exact place of a key quickly, making lookup fast.Final Answer:
Because it allows fast lookup of values by keys -> Option AQuick Check:
Fast key lookup = Because it allows fast lookup of values by keys [OK]
- Thinking hash maps sort data automatically
- Believing hash maps use less memory always
- Assuming hash maps only store numbers
Solution
Step 1: Recall TypeScript Map syntax
In TypeScript, a Map is created usingnew Map<KeyType, ValueType>().Step 2: Check each option
const map = new Map(); uses correct syntax withnew Map<string, number>(). Others have syntax errors or wrong casing.Final Answer:
const map = new Map<string, number>(); -> Option AQuick Check:
Correct Map creation syntax = const map = new Map<string, number>(); [OK]
- Omitting 'new' keyword
- Using lowercase 'map' instead of 'Map'
- Incorrect generic syntax
const map = new Map();
map.set('apple', 5);
map.set('banana', 3);
map.set('apple', 10);
console.log(map.get('apple'));Solution
Step 1: Understand map.set behavior
When setting a key that already exists, the value is updated to the new one.Step 2: Trace the code
First 'apple' is set to 5, then updated to 10. Somap.get('apple')returns 10.Final Answer:
10 -> Option DQuick Check:
Updated value for 'apple' = 10 [OK]
- Assuming first value remains
- Thinking get returns undefined if key repeated
- Expecting error on duplicate keys
const map = new Map();
map['key'] = 'value';
console.log(map.get('key'));Solution
Step 1: Understand how to add entries to Map
Map entries must be added usingmap.set(key, value), not bracket notation.Step 2: Analyze the code behavior
Usingmap['key'] = 'value'adds a property to the object, not a Map entry, somap.get('key')returns undefined.Final Answer:
Using bracket notation to add key-value pairs does not work with Map -> Option CQuick Check:
Use map.set() to add entries [OK]
- Adding entries with bracket notation
- Expecting map.get() to find bracket-added keys
- Thinking Map keys must be numbers
Solution
Step 1: Understand the counting problem
We need to store each word as a key and count as a value, so Map<string, number> fits well.Step 2: How to update counts
For each word, check if it exists in the map; if yes, increment count, else set count to 1.Step 3: Why other options fail
Use an array and push words, then count duplicates manually later is inefficient and manual. Use a Map with word as value and count as key swaps key and value wrongly. Use a Set to store words and count size for each word's Set only stores unique words without counts.Final Answer:
Use a Map<string, number>, for each word check if it exists, then increment or set to 1 -> Option BQuick Check:
Counting words = Map with word keys and number counts [OK]
- Using Set which can't count duplicates
- Swapping key and value types in Map
- Counting manually with arrays inefficiently
Ready to prove it?
Pass the test and this pattern moves unknown
