Use hash maps for O(1) lookups to solve frequency counting and pairing problems
Hash maps provide O(1) average-case lookup, insertion, and deletion. They're essential for tracking frequencies, finding complements, detecting duplicates, and mapping relationships between elements.
Use when you need fast lookups, counting element frequencies, finding pairs with specific relationships, detecting duplicates, or mapping keys to values. Particularly useful for two-sum variants and anagram problems.
Count occurrences of elements to solve frequency-based problems
def frequency_counter(s):
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
return freq
# Example: Valid Anagram
def is_anagram(s, t):
if len(s) != len(t):
return False
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
for char in t:
if char not in freq or freq[char] == 0:
return False
freq[char] -= 1
return True
Find pairs by looking up complements in O(1) time
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
# Example: Four Sum Count
def four_sum_count(A, B, C, D):
sum_ab = {}
# Store all possible sums from A and B
for a in A:
for b in B:
sum_ab[a + b] = sum_ab.get(a + b, 0) + 1
count = 0
# Check complements from C and D
for c in C:
for d in D:
complement = -(c + d)
count += sum_ab.get(complement, 0)
return count
Map elements to their indices or positions for quick lookups
def index_mapping(nums):
index_map = {}
for i, num in enumerate(nums):
if num not in index_map:
index_map[num] = []
index_map[num].append(i)
return index_map
# Example: Contains Duplicate II
def contains_nearby_duplicate(nums, k):
index_map = {}
for i, num in enumerate(nums):
if num in index_map and i - index_map[num] <= k:
return True
index_map[num] = i
return False
def hash_map_template(arr):
hash_map = {}
for i, val in enumerate(arr):
# Frequency counting
hash_map[val] = hash_map.get(val, 0) + 1
# Or complement lookup
complement = target - val
if complement in hash_map:
return [hash_map[complement], i]
# Or index mapping
hash_map[val] = i
return hash_map
Single pass through array with O(1) hash map operations.
Hash map stores up to n elements in worst case.