Hash Maps — The Single Most Useful Data Structure on LeetCode
If you could bring only one data structure to a coding interview, you should bring a hash map. Hash map leetcode problems appear in over 40% of all questions on the platform — not just in the "Hash Table" tag, but embedded inside array problems, string problems, graph problems, and dynamic programming problems. The O(1) average-case lookup is a superpower that transforms brute-force O(n²) solutions into elegant O(n) single-pass algorithms.
Most engineers learn hash maps through Two Sum and then stop. That is a mistake. Two Sum introduces one pattern — complement search — but interviewers test at least five other hash map techniques that are equally important and equally common. If you only know the Two Sum trick, you are leaving points on the table.
This guide covers the six hash map patterns you will encounter in coding interviews. Each pattern includes the mental model, the representative LeetCode problems, and the key insight that makes the pattern click. By the end, you will recognize when a hash map is the right tool — and just as importantly, when it is not.
The 6 Hash Map Patterns Every Interviewer Tests
Hash map interview questions fall into a surprisingly small number of categories. Once you learn to recognize which pattern a problem is testing, the implementation becomes straightforward. Here are the six patterns ranked roughly by frequency in real interviews.
Understanding these patterns is more valuable than memorizing individual solutions. Each pattern gives you a template that applies to dozens of problems, so your preparation time scales efficiently. Instead of grinding 200 problems one at a time, you can master six ideas and apply them everywhere.
- Complement Search — "Does target minus current exist in the map?" (Two Sum family)
- Frequency Counting — Count occurrences, then query the counts (Top K, anagram problems)
- Grouping by Key — Use a computed key to bucket elements together (Group Anagrams)
- Prefix Sum + Hash Map — Track cumulative sums to find subarrays with a target sum
- Two-Pass vs One-Pass — Build the map first then query, or do both simultaneously
- Hash Set for Deduplication — Use a set (hash map with no values) to track seen elements
Complement Search — The Most Important Hash Map Pattern
The complement search pattern is the foundation of hash map interview questions. The idea is simple: for each element you process, ask "does my complement already exist in the map?" If yes, you have found your answer. If no, store the current element and move on. This transforms an O(n²) nested-loop search into an O(n) single-pass solution.
Two Sum (LeetCode #1) is the classic example. You need two numbers that add to a target. For each number, compute target minus that number and check the hash map. If the complement is there, return both indices. If not, store the current number and its index. The entire problem reduces to a single pass through the array.
But complement search goes far beyond Two Sum. Four Sum II (LeetCode #454) uses the same idea with pairs of sums from two arrays stored in a map, then searched against pairs from the other two arrays. The "does my complement exist?" question is the same — only the definition of complement changes. Any problem that asks you to find pairs, triples, or combinations summing to a target is likely a complement search problem in disguise.
The key insight is to always ask: "What value would I need to have seen previously to solve the current step?" If you can define that complement clearly, a hash map will let you check for it in O(1) time.
Pro Tip
The complement search pattern is the most important hash map technique: for each element, ask "does my complement exist in the map?" This single idea solves Two Sum, 4Sum II, and dozens of pair-finding problems.
Frequency Counting — Hash Maps as Histograms
The frequency counting pattern uses a hash map as a histogram: keys are the elements, values are their counts. This is one of the most versatile hash map patterns because counting things is a fundamental operation in an enormous number of problems.
Valid Anagram (LeetCode #242) is the entry-level example. Count the character frequencies of both strings and compare the maps. If they match, the strings are anagrams. Top K Frequent Elements (LeetCode #347) extends this — count frequencies first, then use a heap or bucket sort to extract the top K. The hash map does the hard work of tallying; the second step is just reading the results.
Group Anagrams (LeetCode #49) combines frequency counting with the grouping pattern. You can represent each word by its sorted character sequence or by a frequency tuple, then group all words with the same representation. The frequency count becomes the hash map key itself — a powerful technique for any problem where you need to classify elements by their composition.
In Python, collections.Counter and defaultdict(int) are your best friends for this pattern. In Java, use HashMap with getOrDefault. In JavaScript, use a plain object or Map. The language details vary but the pattern is identical: iterate once, count everything, then query the counts.
Grouping and Indexing — Hash Maps as Lookup Tables
Sometimes the hash map is not storing counts or complements — it is creating an index. The grouping pattern uses a hash map to bucket elements by a computed key so you can look up all elements in a group in O(1) time. This turns problems that seem to require nested comparisons into single-pass solutions.
Isomorphic Strings (LeetCode #205) maps each character in string s to its corresponding character in string t. If a character in s is already mapped to a different character in t, the strings are not isomorphic. The hash map serves as a bidirectional translation table. Word Pattern (LeetCode #290) is the same idea applied to words instead of characters.
The grouping pattern also appears in problems like Group Anagrams (#49) where you need to partition elements. The key insight is choosing the right grouping key. For anagrams, the sorted string works. For isomorphic strings, the mapping itself is the key. For problems involving coordinates, the slope or relative position might be the key. Selecting the right key is the creative step — once you have it, the hash map does the rest.
- Group Anagrams (#49) — group by sorted character sequence or character frequency tuple
- Isomorphic Strings (#205) — map each character to its counterpart, check consistency
- Word Pattern (#290) — map pattern characters to words bidirectionally
- Longest Consecutive Sequence (#128) — use a hash set to check neighbors in O(1)
Did You Know
Hash maps appear in over 40% of LeetCode problems — either as the primary data structure or as an optimization to turn O(n²) nested loops into O(n) single-pass solutions.
Hash Map + Prefix Sum — The Powerful Combo Pattern
The prefix sum plus hash map combination is one of the most elegant patterns in all of LeetCode. It solves problems that ask "how many subarrays have a given sum?" or "find the longest subarray with equal zeros and ones" — questions that seem to require O(n²) brute force but actually yield to O(n) with the right data structures.
Subarray Sum Equals K (LeetCode #560) is the canonical example. As you iterate through the array, maintain a running prefix sum. At each index, ask: "Have I seen a previous prefix sum equal to current_sum minus k?" If yes, then the subarray between that previous index and the current index sums to exactly k. Store prefix sums and their frequencies in a hash map, and the answer accumulates in a single pass.
Contiguous Array (LeetCode #525) applies the same idea to binary arrays. Replace every 0 with -1, then find the longest subarray with sum 0 — which corresponds to equal numbers of 0s and 1s in the original array. The hash map stores the first index where each prefix sum appears, giving you the longest subarray in O(n) time.
The prefix sum pattern is powerful because it converts a range query (sum of elements from i to j) into a point query (difference of two prefix sums). The hash map makes that point query O(1). Whenever you see a problem about subarray sums or subarray properties that can be expressed as cumulative values, reach for this combo.
When NOT to Use Hash Maps — Alternatives and Trade-Offs
Hash maps are powerful, but they are not always the best choice. Knowing when to reach for a different data structure is just as important as knowing the six patterns above. Interviewers sometimes deliberately present problems where a hash map works but a better solution exists — and choosing the optimal approach demonstrates deeper understanding.
If the input data is already sorted, binary search is almost certainly better than a hash map. Binary search uses O(1) extra space and O(log n) time per query. A hash map uses O(n) space for the same task. Two Sum II (LeetCode #167) gives you a sorted array on purpose — the intended solution is two pointers, not a hash map.
When you need elements in sorted order, a hash map cannot help because it does not maintain ordering. Use a TreeMap (balanced BST) or sort the keys explicitly. Problems involving sliding window minimums, ordered statistics, or range queries often require tree-based structures instead.
Memory constraints matter too. Hash maps use O(n) extra space, and in languages like Java, the overhead per entry can be significant due to boxing and node objects. If the problem specifies very tight memory limits or asks for an in-place solution, consider bit manipulation, two pointers, or sorting-based approaches instead. Practice these patterns with YeetCode flashcards to build the intuition for choosing the right tool for each problem.
- Sorted input — use binary search or two pointers instead (O(1) space vs O(n))
- Need ordered keys — use TreeMap or balanced BST (hash map vs tree map trade-off)
- Memory-constrained — consider sorting, two pointers, or bit manipulation
- Simple deduplication of small ranges — a boolean array may be faster than a hash set
Watch Out
Hash maps use O(n) extra space and have O(n) worst-case for hash collisions — if the problem constraints are very tight on memory, or data is already sorted, consider alternatives like binary search or two pointers.