Technique
Hash Map / Hash Set Lookup
Store seen values (or counts, or first index) in a hash map so 'have I seen x / how many x' is O(1) expected.
0/47 solved
Recognise it
The signal
pair with target sum in an UNSORTED array
1Brute force
Nested loop comparing all pairs O(n2) or sorting O(n log n).
2The observation
Repeated searching: a hash lookup replaces an inner loop.
3Why it works
The map contains exactly the elements (or prefix values) of the processed part.
Reach for it when
- +duplicates / anagrams / grouping by a canonical key
- +frequency comparisons
- +first index of a prefix value
Not when
- ×need ordering / nearest value (ordered-set or binary search)
- ×adversarial inputs against unordered_map on Codeforces (use custom hash)
Practice
- Two SumAmazon, GoogleEasy
- Contains DuplicateAmazon, AdobeEasy
- Contains Duplicate IIAmazon, AdobeEasy
- Isomorphic StringsGoogle, AmazonEasy
- Ransom NoteAmazon, AppleEasy
- Design HashMapAmazon, MicrosoftEasy
- First Unique Character in a StringAmazon, MicrosoftEasy
- Intersection of Two ArraysMeta, AdobeEasy
- Logger Rate LimiterPremiumEasy
- Valid AnagramAmazon, UberEasy
- Word PatternGoogle, UberEasy
- Sum of Two ValuesCSESEasy
Pitfalls
Misconceptions
- !hashing a mutable key
- !two-sum: inserting before checking pairs an element with itself
Looks like it, isn't
- Majority Element needs Boyer-Moore Majority Vote
Why
Counting works but O(1) space is possible with pairwise cancellation. - Can Make Palindrome from Substring needs Prefix Sum
Why
Per-query counting is O(26n). Prefix parity masks answer each query by the popcount of an XOR. source ↗
Go deepervariants and techniques · 10 combinations · resources
Combinations
Prefix Sum+Hash Map / Hash Set Lookup
count/longest subarrays with sum (or mod, or balance) equal to a target, negatives allowed
- Prefix Sum:
- turns every subarray into a pair of prefixes
- Hash Map / Hash Set Lookup:
- counts earlier prefixes with the needed value in O(1)
Subarray Sum Equals KContiguous ArraySubarray Sums Divisible by K
Sliding Window+Hash Map / Hash Set Lookup
longest/shortest substring with distinct/at-most-K/covers-all-chars condition
- Sliding Window:
- maintains a valid contiguous window
- Hash Map / Hash Set Lookup:
- keeps character/value frequencies for the validity test
Longest Substring Without Repeating CharactersMinimum Window SubstringPermutation in String
Tree DFS (Paths & Recursion)+Prefix Sum+Hash Map / Hash Set Lookup
count downward paths with a given sum
- Tree DFS (Paths & Recursion):
- walks root-to-node paths
- Prefix Sum:
- path sums as prefix differences
- Hash Map / Hash Set Lookup:
- counts prefix values on the current path
Mo's Algorithm (offline range queries)+Prefix Sum+Hash Map / Hash Set Lookup
count subarrays in [l, r] with a pair property, many offline queries
- Mo's Algorithm (offline range queries):
- moves the query window
- Prefix Sum:
- subarray XOR as prefix XOR pair
- Hash Map / Hash Set Lookup:
- frequency counts of prefix values in the window
Hash Map / Hash Set Lookup+System / DS Design
LRU/LFU caches
- Hash Map / Hash Set Lookup:
- maps each key to its list node in O(1)
- System / DS Design:
- a doubly linked list spliced in O(1) keeps recency order (LFU: one list per frequency)
Prefix Sum+Bit Tricks & Bitmasking+Hash Map / Hash Set Lookup
substrings/subarrays where every letter (or bit) occurs an even number of times, or at most one is odd
- Prefix Sum:
- a substring's parity is prefix[j] ^ prefix[i]
- Bit Tricks & Bitmasking:
- a parity mask of the character counts replaces a count vector
- Hash Map / Hash Set Lookup:
- first index (or count) of each mask seen so far
Find the Longest Substring Containing Vowels in Even CountsNumber of Wonderful SubstringsCount the Number of Beautiful Subarrays
Few Distinct Subarray OR / AND / GCD Values+Hash Map / Hash Set Lookup
distinct subarray ORs, or the number of subarrays with AND equal to k
- Few Distinct Subarray OR / AND / GCD Values:
- at most log V distinct OR/AND values end at each index
- Hash Map / Hash Set Lookup:
- collect the distinct values, or count those equal to k
Bitwise ORs of SubarraysNumber of Subarrays With AND Value of K
Few Distinct Subarray OR / AND / GCD Values+GCD / LCM & Euclid+Hash Map / Hash Set Lookup
the number of subarrays whose gcd equals x, for many x
- Few Distinct Subarray OR / AND / GCD Values:
- O(log V) (gcd, count) pairs per right end
- GCD / LCM & Euclid:
- the gcd as j moves left only drops to a divisor
- Hash Map / Hash Set Lookup:
- global count of subarrays per gcd value
Randomised Set Hashing (XOR / sum hashing, Zobrist)+Prefix Sum+Two Pointers
subarrays that are permutations, or where every value occurs exactly k times
- Randomised Set Hashing (XOR / sum hashing, Zobrist):
- random labels make set identity additive
- Prefix Sum:
- a subarray's hash is a prefix difference/XOR
- Two Pointers:
- keep the window where no value exceeds k occurrences (1418G)
Mo's Algorithm (offline range queries)+Euler Tour / Tree Flattening+Hash Map / Hash Set Lookup
many offline path queries counting pairs/distinct values on tree paths
- Mo's Algorithm (offline range queries):
- path = range with odd-toggle membership plus the LCA
- Euler Tour / Tree Flattening:
- a 2n entry/exit sequence
- Hash Map / Hash Set Lookup:
- frequency counts by value or gender pair