Hash sets and maps in practice: counting, lookup, deduplication
Hash sets and maps answer "have I seen this?" in O(1). Use them to count, look up, group and deduplicate, as in Two Sum.
Before you start: Load factor and resizing.
The idea
The fourth value is 8: have you seen it before? A hash map answers without rereading the array.
Many array problems ask this question for every element. A hash set or map answers it in about one step.
Intuition
Without a map, each question scans the list. 7 values mean up to 7 looks, for every value.
With a map, 7 mod 7 = 0 points straight to bucket 0. One look tells you whether 7 is stored.
A set stores keys only. A map stores a value next to each key, such as a count or an index.
Complexity
Each map question costs about 1 step. A pass over n values costs O(n) time and O(n) space for the map.
The map trades memory for speed. Scanning needs no extra space but costs O(n) per question, so O(n²) in total.
Pitfalls
Check the map before you store the current value. Here 3 was stored first, so its lookup for 3 finds itself.
Variations
Use a computed key. Words with the same sorted letters share a key, so the map groups the anagrams.
Code
Pseudocode
counts ← empty map
for each x in values
counts[x] ← counts.get(x, 0) + 1
return counts
Python
def count(values):
counts = {}
for x in values:
counts[x] = counts.get(x, 0) + 1
return counts
JavaScript
function count(values) {
const counts = new Map();
for (const x of values) {
counts.set(x, (counts.get(x) ?? 0) + 1);
}
return counts;
}
Cost at a glance
| Access | n/a |
|---|---|
| Search | O(1) avg |
| Insert | O(1) avg |
| Delete | O(1) avg |
| Space | O(n) |
Practice problems (7)
Contains duplicate Warm-up
Given an integer array nums, return true if any value appears at least twice. Return false if every value is distinct.
Build a frequency map Warm-up
Follow a frequency map as it reads [4, 2, 4, 4, 2, 9]. The map has 7 buckets and hashes a key with key mod 7. Answer each question before the step plays.
Two Sum Standard
Given an integer array nums and an integer target, return the indices [i, j] with i < j of the two values that add up to target.
At most one pair works. Return [] if no pair exists. Do not use the same cell twice.
First unique character Standard
Given a string s, return the index of the first character that appears exactly once in s. Return -1 if no character is unique.
Group anagrams Standard
Given an array of strings words, group the words that are anagrams of each other. Two words are anagrams when they use the same letters the same number of times.
Return the groups in any order, with the words inside each group in any order.
Intersection of arrays Standard
Given two integer arrays nums1 and nums2, return the values that appear in both. Each value appears once in the result, in any order.
Longest consecutive sequence Challenge
Given an unsorted integer array nums, return the length of the longest run of consecutive integers, such as 1, 2, 3, 4. The run can use values from any positions.
The solution must run in O(n) time, so sorting is not allowed.
Related topics
- Collisions, worst cases and mutable keys
- Tries: insert, search, prefix
- Overlapping subproblems and memoization
Next on the path: Collisions, worst cases and mutable keys