🌇DSA
← Back
Data StructureBeginner
🗂️

HashMap & HashSet

Fast lookup using keys

⏱️ 4–6 hours🧩 10 LeetCode
🔒 Login to unlock solutions and track progress. Login

What is it?

A HashMap is like a phone book — you look up a key and instantly get its value. Average lookup is O(1) no matter how big it grows.

A HashSet is like a bag of stickers — it only keeps unique values, automatically discarding duplicates.

Real-World Examples

Phone contact lookup
Word frequency counter
Remove duplicates from list
Cache API responses
Group items by category
Track visited graph nodes

Code Example

What this code shows

Count how many times 'apple' appears by incrementing its map entry twice. Then put [1, 2, 2, 3] into a set — the duplicate 2 is dropped automatically, leaving 3 unique items.

// ── HashMap: count word occurrences ──
const map = new Map();

// increment count each time we see 'apple'
map.set("apple", (map.get("apple") ?? 0) + 1); // apple → 1
map.set("apple", (map.get("apple") ?? 0) + 1); // apple → 2

console.log("apple count:", map.get("apple")); // 2

// ── HashSet: keep only unique values ──
const set = new Set([1, 2, 2, 3]); // duplicate 2 is dropped

console.log("Set size:", set.size);  // 3  (not 4)
console.log("Has 2:   ", set.has(2)); // true

Expected Output

apple count: 2
Set size:    3
Has 2:       true

LeetCode Practice