Why Hash Map Exists and What Problem It Solves in DSA Javascript - Performance Analysis
We want to understand why hash maps are useful by looking at the time it takes to find data.
What problem does a hash map solve when searching or storing data?
Analyze the time complexity of searching for a value in an array versus using a hash map.
// Searching in an array
function findInArray(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return true;
}
return false;
}
// Using a hash map
const map = new Map();
map.set('key', 'value');
const found = map.has('key');
The first function searches through each item one by one. The second uses a hash map to check quickly.
Look at what repeats when searching for data.
- Primary operation: Looping through the array items one by one in
findInArray. - How many times: Up to
ntimes, wherenis the number of items. - Hash map operation: Direct lookup using a hash function, no loop needed.
As the list gets bigger, searching by checking each item takes longer.
| Input Size (n) | Approx. Operations (Array Search) |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows directly with the number of items.
For hash maps, the lookup stays almost the same time regardless of size.
Time Complexity: O(n) for array search, O(1) for hash map lookup
This means searching in an array takes longer as it grows, but hash maps find items quickly no matter the size.
[X] Wrong: "Searching an array is always fast enough, so hash maps are not needed."
[OK] Correct: When the list is large, searching each item one by one becomes slow, making hash maps much faster for lookups.
Understanding why hash maps exist shows you know how to choose the right tool for fast data access, a key skill in coding and problem solving.
"What if the array was sorted? How would the time complexity of searching change compared to using a hash map?"
Practice
hashMap = {}Solution
Step 1: Understand the purpose of a hash map
A hash map stores data as key-value pairs, allowing quick access to values using keys.Step 2: Compare with other data structures
Unlike lists or arrays, hash maps provide faster lookup by key, not by position or order.Final Answer:
To store key-value pairs for fast data lookup -> Option AQuick Check:
Hash map = fast key-value lookup [OK]
- Thinking hash maps sort data automatically
- Confusing hash maps with arrays or lists
- Assuming hash maps are for math calculations
Solution
Step 1: Recall JavaScript syntax for objects
In JavaScript, curly braces {} create an empty object, which can be used as a hash map.Step 2: Check other options
Square brackets [] create arrays, () => {} is a function, and new Map[] is invalid syntax.Final Answer:
const map = {} -> Option BQuick Check:
Empty object = {} [OK]
- Using [] which creates an array, not a hash map
- Trying to use function syntax for hash map
- Incorrect new Map[] syntax
const map = {};
map['apple'] = 5;
map['banana'] = 3;
console.log(map['apple']);Solution
Step 1: Assign values to keys in the hash map
The code sets map['apple'] = 5 and map['banana'] = 3, storing these key-value pairs.Step 2: Access the value for key 'apple'
console.log(map['apple']) prints the value 5 stored at key 'apple'.Final Answer:
5 -> Option AQuick Check:
map['apple'] = 5, output = 5 [OK]
- Expecting output to be 'undefined' if key exists
- Confusing values of different keys
- Thinking it causes an error
const map = {};
map.apple = 10;
console.log(map['applee']);Solution
Step 1: Check key assignment
map.apple = 10 correctly assigns value 10 to key 'apple'.Step 2: Check key access
console.log(map['applee']) tries to access key 'applee' which was never assigned, so it returns undefined.Final Answer:
Accessing a key that does not exist -> Option DQuick Check:
Wrong key access = undefined [OK]
- Thinking dot notation is wrong here
- Expecting error on accessing missing key
- Assuming empty object cannot store values
const words = ['cat', 'dog', 'cat', 'bird'];
const counts = {};
// Fill counts here
console.log(counts);Solution
Step 1: Understand counting logic
We need to add 1 to the count for each word. If the word is new, start from 0.Step 2: Analyze each option
for (const w of words) { counts[w] = 1; } sets count to 1 always, ignoring repeats. for (const w of words) { counts[w] = counts[w] + 1; } tries to add 1 but counts[w] is undefined initially causing NaN. for (const w of words) { counts[w] = (counts[w] || 0) + 1; } uses (counts[w] || 0) + 1 to handle undefined keys correctly. for (const w of words) { counts[w] += 1; } tries to add 1 without initialization, causing NaN.Final Answer:
for (const w of words) { counts[w] = (counts[w] || 0) + 1; } -> Option CQuick Check:
Initialize with 0 or use || 0 before adding [OK]
- Not initializing counts before adding
- Overwriting counts instead of incrementing
- Assuming counts[w] is always defined
Ready to prove it?
Pass the test and this pattern moves unknown
