Hash Maps
Hash Maps (objects in JavaScript) store key-value pairs for O(1) lookup: instant access regardless of size. Use them for counting, grouping, and caching.
// Count character frequency
function charCount(str: string): Record<string, number> {
const count: Record<string, number> = {}
for (const char of str) {
count[char] = (count[char] || 0) + 1
}
return count
}
charCount("hello")
// { h: 1, e: 1, l: 2, o: 1 }
// Find first non-repeating character
function firstUnique(str: string): string {
const count = charCount(str)
for (const char of str) {
if (count[char] === 1) return char
}
return ""
}