ποΈ Day 44 Bonus: Hash Maps β Keys, Values, and O(1) Lookup Magic
π§ Concept Deep Dive
A Hash Map is like a magical dictionary: you give it a key, it gives you back a valueβinstantly. Hash maps allow us to store data in key => value format with average O(1) lookup, insert, and delete operations.
They're incredibly useful for:
- Counting frequencies
- Detecting duplicates
- Fast lookups
- Caching
- Grouping data by keys
π Core Concepts
Declaring Hash Maps in TypeScript
// Using object literal
const obj: Record<string, number> = {};
obj["apple"] = 3;
obj["banana"] = 5;
// Using Map class
const map = new Map<string, number>();
map.set("apple", 3);
map.set("banana", 5);Retrieving and Checking Keys
console.log(obj["apple"]); // 3
console.log("banana" in obj); // true
console.log(map.get("apple")); // 3
console.log(map.has("banana")); // trueDeleting
delete obj["apple"];
map.delete("apple");Iterating Over Map
for (const [key, value] of map.entries()) {
console.log(`${key}: ${value}`);
}π§ Real-World Use Case: Frequency Counter
function countFrequencies(arr: string[]): Record<string, number> {
const freq: Record<string, number> = {};
for (const item of arr) {
freq[item] = (freq[item] || 0) + 1;
}
return freq;
}
console.log(countFrequencies(["a", "b", "a", "c", "b", "a"]));
// Output: { a: 3, b: 2, c: 1 }π¨ ASCII Visualization
Key => Value
"banana" => 5
"apple" => 3
"orange" => 1Think of a map like labeled boxes. You can instantly find what's inside by reading the label.
ποΈ Homework (LeetCode-style)
Problem 1: Two Sum
function twoSum(nums: number[], target: number): number[] {
const map = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement)!, i];
}
map.set(nums[i], i);
}
return [];
}Input: nums = [2,7,11,15], target = 9 β Output: [0,1]
Problem 2: Isomorphic Strings
function isIsomorphic(s: string, t: string): boolean {
const mapST = new Map();
const mapTS = new Map();
for (let i = 0; i < s.length; i++) {
const c1 = s[i];
const c2 = t[i];
if ((mapST.get(c1) ?? c2) !== c2 || (mapTS.get(c2) ?? c1) !== c1) {
return false;
}
mapST.set(c1, c2);
mapTS.set(c2, c1);
}
return true;
}Input: "egg", "add" β Output: true
Problem 3: First Unique Character
function firstUniqChar(s: string): number {
const count: Record<string, number> = {};
for (const char of s) count[char] = (count[char] || 0) + 1;
for (let i = 0; i < s.length; i++) {
if (count[s[i]] === 1) return i;
}
return -1;
}Input: "leetcode" β Output: 0
π Summary
- Hash maps allow O(1) average lookup and insert.
- Use
Record<string, T>orMap<K, V>in TypeScript. - Perfect for frequency counting, duplicate detection, and quick access.