Topic 14 of 14
Hashing Patterns
1 pattern and 5 practice problems, each with a recall tip, a diagram, the theory and a Python template.
01
Hashing - Frequency Count / Grouping
5 practice problems
Theory
- Count occurrences with a hash map (Counter in Python). O(1) lookup per element.
- Group elements by a computed key (e.g., sorted string for anagrams).
- Two Sum pattern: for each element, check if complement exists in the map.
- Prefix sum + hash map: count subarrays with a given sum in O(n).
Code template
python
from collections import Counter, defaultdict
def group_anagrams(strs):
groups = defaultdict(list)
for s in strs:
key = tuple(sorted(s))
groups[key].append(s)
return list(groups.values())
def subarray_sum(nums, k):
prefix = {0: 1}
total = count = 0
for num in nums:
total += num
count += prefix.get(total - k, 0)
prefix[total] = prefix.get(total, 0) + 1
return countPractice problems · 5
Spotted a mistake on this page?
Wrong formula, broken animation or confusing wording. Tell us and we will fix it.