---
title: "Hash map problems, worked"
url: "https://georgeliinternships.com/interview-prep/coding/hash-maps.md"
canonical_url: "https://georgeliinternships.com/interview-prep/coding/hash-maps"
last_updated: "2026-12-01"
type: "guide"
summary: "Hash maps for coding interviews: how hashing and collisions work, a complexity cheat sheet, problems from easy to hard and four checked practice problems."
related: ["https://georgeliinternships.com/interview-prep.md", "https://georgeliinternships.com/methodology.md", "https://georgeliinternships.com/roles.md"]
---

# Hash maps in coding interviews: how they work, with practice problems

> **For AI agents:** the complete index of George Li Internships pages is [llms.txt](https://georgeliinternships.com/llms.txt). Every page is also served as markdown at its URL plus .md.

Hash maps for coding interviews: how hashing and collisions work, a complexity cheat sheet, problems from easy to hard and four checked practice problems.

Hash maps and ordered maps show up across nearly every software engineering interview loop because fast lookups turn slow nested loops into linear passes. This guide walks through map internals, collision handling, a complexity cheat sheet, 50 classic coding prompts across every difficulty tier, and a timed practice routine.

## How maps and hash tables store and retrieve keys

A map associates each unique key with a stored value, letting you look up records by label rather than numeric position. Whereas an array retrieves elements by integer offset, a map lets you query by a string, tuple, object identifier, or sparse integer. Everyday software relies on this pattern for contact directories, user credential stores, routing tables, and character frequency counters.

### Hash functions, buckets, and dynamic resizing

The most widely used map variant is the hash map, often called a hash table. Under the hood, it allocates a backing array of fixed slots, commonly known as buckets. When you store a pair, the map passes your key through a deterministic hash function that converts arbitrary input into a bounded integer index inside that array.

Suppose you map student names to locker numbers and the hash function sends the key “Alice” to bucket 5. You place “Alice” and her locker number directly at array slot 5, leaving unused slots around it empty. Because computing the hash and reading slot 5 take constant steps regardless of how many students are stored, average lookup, membership checks, insertion, and deletion all finish in O(1) time instead of scanning an entire list in O(n) time.

A hash map stays fast only as long as the backing array has breathing room. Once stored entries cross a threshold relative to capacity, the table allocates a larger backing array, typically twice the previous size, and rehashes every existing key into its new slot. That resize operation takes linear time, though it happens infrequently enough that average insertions remain constant.

### Handling hash collisions with chaining and open addressing

Because an infinite variety of keys must map into a finite array of buckets, two distinct keys occasionally hash to the exact same slot. Every practical hash table implements a collision strategy to keep data intact when this happens:

- Separate chaining: Each bucket holds a pointer to a linked list or secondary chain of entries. A lookup jumps to the hashed bucket in O(1) time and walks that short chain until it finds the matching key.
- Open addressing: All entries sit directly inside the backing array. When a target bucket is already occupied, the table probes forward through subsequent slots, wrapping back to index 0 at the end of the array, until it reaches an open slot.

Imagine slot 3 already stores “David” and you insert “Nina”, whose key also hashes to 3. With separate chaining, you append “Nina” onto the linked list rooted at slot 3. With linear open addressing, you check slot 4; if free, you store “Nina” there, or keep advancing past occupied slots and wrapping around to index 0 if the array tail is full.

### Ordered tree maps and language implementations

Not every map relies on hashing. A tree map keeps keys inside a self-balancing binary search tree, most commonly a red-black tree, so keys stay sorted automatically. Lookups, insertions, and deletions cost O(log n) instead of O(1), yet ordered traversal lets you query minimum keys, maximum keys, or key ranges efficiently, which an unordered hash table cannot do natively.

Interviewers expect you to know the concrete map types built into your chosen coding language:

- Java: The Map interface is implemented by HashMap (unsynchronized, permits a single null key), Hashtable (thread-safe, rejects null keys), and TreeMap (red-black tree providing O(log n) operations in sorted key order).
- C++: The standard library provides std::map as a red-black tree map with sorted keys and std::unordered_map as an average O(1) hash table added in C++11.
- Python: The built-in dict is a hash table implementation that accepts heterogeneous immutable keys such as strings, numbers, and tuples, while collections.defaultdict automatically supplies a default value when reading an unseen key.

### When simpler structures beat a map

Maps carry extra memory and constant-factor overhead compared to plain arrays or linked lists. When you index sequential positions or iterate linearly over small fixed collections, an array is leaner and faster. In addition, hash maps waste memory on empty buckets when sparsely populated, and a poorly chosen hash function can dump every entry into a single bucket chain, degrading lookup speed to a linked-list scan with extra hashing overhead.

> **Choose the right map.** Default to a hash map when you only need exact key lookups or frequency counts. Switch to a tree map only when the prompt requires sorted keys, floor and ceiling queries, or ordered range iteration.

## Map complexity, hashing techniques, and algorithms cheat sheet

Memorizing Big-O tables without knowing why those bounds happen falls apart as soon as an interviewer asks a follow-up question about collisions or memory usage. Keep these time, space, and algorithmic mechanics clear before your loop.

| Operation or metric | Hash map (average) | Hash map (worst case) | Tree map (red-black tree) |
| --- | --- | --- | --- |
| Search by key | O(1) | O(n) | O(log n) average and worst, O(1) at root |
| Insert key-value pair | O(1) | O(n) | O(log n) average and worst |
| Update existing value | O(1) | O(n) | O(log n) average and worst |
| Delete key | O(1) | O(n) | O(log n) average and worst |
| Space complexity | O(n) | O(n) | O(n) |
*Time and space complexity comparison between hash maps and balanced tree maps*

### Why hash maps degrade and tree maps stay predictable

Under good hash distribution, collisions per bucket remain bounded by a small constant, keeping reads, writes, updates, and deletes at O(1). In the pathological worst case, every key hashes to the same slot, forcing separate chaining or open addressing to inspect all n stored entries in O(n) time before finding a match or confirming absence.

A red-black tree keeps tree height bounded by O(log n). Because roughly half of all nodes sit at the leaf level, average and worst-case traversals for search, insertion, update, and deletion stay O(log n), with only a root match finishing in O(1) time. On space, hash tables allocate sparse backing arrays whose capacity stays within roughly twice the active element count, so both hash maps and tree maps use O(n) space overall.

### Core hashing concepts and related techniques

Beyond basic dictionary lookups, interviewers regularly connect maps to these supporting data structures and hashing algorithms:

- Hash sets: Store unique keys without associated values for O(1) membership checks and deduplication.
- Bloom filters: Space-compact probabilistic structures using multiple hashes to test membership with possible false positives but zero false negatives.
- Load factor and rehashing: The ratio of stored items to total buckets that triggers doubling and reindexing to avoid long chains.
- Collision resolution variants: Separate chaining, open addressing with linear probing, and double hashing using a second hash step to reduce clustering.
- Specialized hash functions: Pearson hashing for compact byte tables, plus rolling hashes and the Rabin-Karp algorithm for sliding substring searches.
- Distributed hashing: Consistent hashing rings and load balancing to map keys across changing server nodes with minimal key movement.
- Complementary interview techniques: Boyer-Moore majority voting for O(1)-space dominance checks, sliding windows paired with frequency maps, dynamic programming memoization, language-specific collision handling in Java, and Python defaultdict counters.

### Bucket sort and binary search connections

Bucket sort (also called bin sort) mirrors a chaining hash table: items are distributed across k ordered bins, each bin is sorted individually (commonly with insertion sort), and all k bins are concatenated into the output array. Distribution takes O(n) and collecting across bins takes O(k). When every bin holds at most one item, per-bin sorting is O(1) and total runtime is O(n + k); if every item lands in a single bin, insertion sort degrades to O(n^2).

Binary search also appears whenever a map falls back to a balanced search tree or a sorted overflow structure. Each failed comparison cuts the remaining candidate range in half, yielding O(log n) search time unless the target sits at the tree root or exact array midpoint.

## Six typical map interview prompts to practice first

Before diving into dozens of specialized exercises, verify that you can solve six foundational map patterns cleanly from scratch. Each prompt below illustrates a distinct way maps eliminate brute-force work:

1. Pair sum check: Given an integer list and a target total, decide whether two distinct entries add up to that target. For instance, with [8, 12, 4, 9] and target 13, return true because 4 + 9 = 13. Store each visited number in a hash set and check whether target minus the current value already exists.
2. Dominant element lookup: Given a list of length n, find the value appearing more than n / 2 times. Tally counts in a hash map or pair a candidate tracker with Boyer-Moore voting for constant extra space.
3. Least Recently Used cache: Design an LRU cache initialized to capacity C where both reads and writes execute in O(1) time. Pair a hash map pointing keys to nodes with a doubly linked list ordered from newest to oldest access.
4. Duplicate check: Given an integer array, report true when any number occurs two or more times and false when all items are unique. Insert values sequentially into a hash set and stop as soon as an item is already present.
5. Earliest element reaching frequency k: Given n integers spanning arbitrary ranges and a threshold k, print the first item that appears k times overall, or -1 if none hits that count. Count frequencies in a hash map first, then scan the array left to right to locate the earliest element matching k.
6. All valid word splits: Given a string and a word bank, insert spaces to produce every valid sentence formed exclusively from dictionary words in any order. Combine a hash set of dictionary words with memoized recursion or dynamic programming to avoid recomputing suffixes.

> **Avoid passive solution reading.** Treat every practice prompt like a timed screen: set a clock, write code without looking up answers, and only inspect an editorial after a genuine attempt so you build problem-solving recall instead of solution memorization.

## Easy map interview questions for phone screens

Phone screens often start with focused easy problems that test whether you recognize when a hash map or hash set replaces an O(n^2) nested scan with a single O(n) pass. Practice talking through edge cases clearly without relying on a compiler.

1. Two Sum: Scan once while mapping each value to its index. Look up target - x at each step to return matching indices in O(n) time.
2. Roman to Integer: Map each Roman symbol to its decimal value, then walk left to right and subtract whenever the next symbol is larger.
3. Majority Element: Tally counts in a hash map to find the value exceeding n / 2 occurrences, or use Boyer-Moore voting for O(1) space.
4. Happy Number: Repeatedly sum squared digits while storing seen totals in a hash set; hitting 1 succeeds while any repeat proves a cycle.
5. Contains Duplicate: Insert elements into a hash set and return true the instant an item already exists.
6. Valid Anagram: Compare character counts across both strings with a hash map or 26-slot array so any mismatch fails fast.
7. Intersection of Two Arrays II: Count the shorter array in a hash map, then scan the second array and decrement shared counts.
8. First Unique Character in a String: Build a frequency map in one pass, then scan left to right to return the first count of 1.
9. Isomorphic Strings: Pair a forward map with a used-target set so every character maps consistently without two characters sharing one target.
10. Employee Importance: Index employee records by ID in a hash map, then run BFS or DFS from the root ID to sum importance scores.
11. Contains Duplicate II: Map each value to its latest index and return true when a repeat appears within distance k.
12. Word Pattern: Split the string into words and enforce a bijection between pattern characters and words using two maps.
13. Longest Palindrome: Sum the largest even count for each character in a frequency map, then add 1 if any odd count remains.
14. Next Greater Element I: Run a monotonic stack on the superset array to populate a next-greater map, then answer queries in O(1) time.
15. Keyboard Row: Map each letter to row 1, 2, or 3 and keep words whose characters share one row ID.
16. Longest Harmonious Subsequence: Count each integer in a map and maximize count[x] + count[x + 1] across existing keys.

## Medium map interview questions for live coding rounds

Video screens and onsite coding interviews lean heavily on medium prompts that pair hash maps with sliding windows, linked lists, prefix sums, or custom data structure design. Expect follow-up questions on worst-case hashing and memory tradeoffs.

1. Longest Substring Without Repeating Characters: Slide a window while mapping each character to its latest index, jumping the left pointer past active duplicates.
2. Valid Sudoku: Track seen digits in row, column, and 3x3 box hash sets (or encoded tuple keys) during one board scan.
3. Group Anagrams: Map a canonical key, such as sorted characters or a 26-count tuple, to each list of matching words.
4. Longest Consecutive Sequence: Load values into a hash set and count upward only from starts where x - 1 is absent for O(n) total time.
5. LRU Cache: Pair a key-to-node hash map with a doubly linked list so reads, writes, and tail evictions run in O(1) time.
6. Fraction to Recurring Decimal: Map each division remainder to its output index; when a remainder repeats, wrap that slice in parentheses.
7. Top K Frequent Elements: Tally counts in a frequency map, then extract the top k keys via frequency buckets in O(n) time or a size-k heap.
8. Insert Delete GetRandom O(1): Combine an array with a value-to-index map; on delete, swap the item with the last element and pop.
9. 4Sum II: Store pairwise sums from the first two arrays in a frequency map, then look up negated sums from the remaining two arrays.
10. Copy List with Random Pointer: Map each original node to its clone in a hash map so a second pass connects next and random pointers.
11. Word Break: Load dictionary words into a hash set and run dynamic programming across prefixes to verify full segmentation.
12. Find All Anagrams in a String: Compare a fixed-width sliding window frequency map against the target word’s counts.
13. Subarray Sum Equals K: Track running prefix sums in a frequency map and add count[prefix - k] at each index.
14. Task Scheduler: Count frequencies in a map to anchor idle slots around the max frequency, or simulate cooldowns with a max-heap and queue.
15. Partition Labels: Map each letter to its final index and extend the active slice until your cursor reaches the farthest saved end.
16. Repeated DNA Sequences: Slide a 10-character window using a seen hash set or rolling 2-bit integer encoding to collect repeated substrings.
17. Bulls and Cows: Count exact index matches as bulls, then tally remaining digit frequencies in maps to total overlapping cows.

## Hard map interview questions for onsite interviews

Hard prompts rarely rely on a single dictionary alone. Interviewers combine hash maps with bidirectional graph search, multi-tier eviction structures, prefix-sum matrices, and trie or palindrome lookups, giving you more time to reason through edge cases.

1. Minimum Window Substring: Track required letter counts in a map, expand right until covered, then shrink left to capture the shortest valid span.
2. Word Ladder: Bucket dictionary words by single-character wildcard patterns in an adjacency map so BFS finds the shortest transformation chain.
3. Word Break II: Store words in a hash set and cache valid suffix sentences in a memoization map to avoid rebuilding repeated tails.
4. Max Points on a Line: Anchor each point and map reduced slope fractions (dx/gcd, dy/gcd) to point counts while handling verticals and duplicates.
5. Substring with Concatenation of All Words: Count target words in a reference map and slide word-length windows from each offset modulo word size.
6. Word Ladder II: Run BFS with level-visited maps recording parent links for shortest paths, then backtrack from the target to collect all sequences.
7. Palindrome Pairs: Map reversed words to indices, then check prefix and suffix splits where the residual piece is a palindrome and the mirror exists.
8. LFU Cache: Pair a key-to-node map with a frequency-to-doubly-linked-list map and track minimum frequency for O(1) eviction.
9. Random Pick with Blacklist: Remap blacklisted indices below the valid range onto unblocked upper-tail values via a hash map for O(1) picks.
10. Number of Atoms: Parse nested chemical formulas using a stack of count maps, multiplying inner maps by trailing digits at each closing parenthesis.
11. Bus Routes: Map each stop ID to all routes serving it, then run BFS across routes to minimize total transfers.
12. Maximum Frequency Stack: Combine a value-to-frequency map with a frequency-to-stack map, popping from the highest active frequency tier.
13. Subarrays with K Different Integers: Compute atMost(K) minus atMost(K - 1) using a sliding window and frequency map.
14. Grid Illumination: Track active lamps in a set plus four maps counting rows, columns, and both diagonals (r - c and r + c) for O(1) queries.
15. Number of Submatrices That Sum to Target: Fix pairs of rows, collapse columns into 1D sums, and apply prefix-sum hash map counting across columns.
16. Minimum Operations to Make a Subsequence: Map target values to unique indices, convert the second array, and find the longest increasing subsequence in O(n log n).
17. Maximum Equal Frequency: Track element-to-frequency and frequency-to-group-size maps so each step tests valid equal-frequency states in O(1) time.

> Hard map problems rarely invent new dictionary tricks; they pair simple hash map lookups with sliding windows, prefix sums, or graph traversal.

## Four practice problems, in order of difficulty

These are our own practice problems, written for this site. Try each on paper first, then open the working. The set runs from counting pairs to the longest run, and each one asks for a number so that the answer can be checked.

**Problem 1.** The list is 3, 5, 2, 5, 8, 0, 5, 6, 3, 2. How many pairs of positions i < j have a[i] + a[j] equal to 8? Two equal values at different positions count as a pair. Give an integer.

**Answer:** 9

1. Walk the list once with a dictionary of how many times each value has appeared so far. For each new value x, the earlier values that complete it are the ones equal to 8 - x, so add the dictionary count for 8 - x to the total, then record x.
2. In order: 3 finds no 5 yet (total 0). 5 finds one 3 (1). 2 finds no 6 (1). 5 finds one 3 (2). 8 finds no 0 (2). 0 finds one 8 (3). 5 finds one 3 (4). 6 finds one 2 (5).
3. The next 3 finds three 5s, so it adds 3 (8). The last 2 finds one 6 (9).
4. The answer is 9. Checking every pair would take O(n^2); the dictionary makes one pass of O(n) with O(1) average lookups.

**Problem 2.** Twelve words are given: listen, silent, enlist, google, gogole, cat, act, tac, dog, god, odg, bird. Two words belong to the same group when one is an anagram of the other, meaning it uses exactly the same letters the same number of times. How many groups are there? Give an integer.

**Answer:** 5

1. Use as the dictionary key each word with its letters sorted. Words that are anagrams share a key, so a dictionary from key to list of words puts them in one place.
2. The key for listen, silent and enlist is eilnst. The key for google and gogole is eggloo. The key for cat, act and tac is act. The key for dog, god and odg is dgo. The key for bird is bdir.
3. That is 5 keys, so 5 groups: sizes 3, 2, 3, 3 and 1. A word with no anagram still forms a group of one.
4. Sorting each word of length L costs O(L log L), and the grouping takes one pass over the words.

**Problem 3.** In the text pwwkewabcdabxyzzyx, what is the length of the longest stretch of consecutive characters in which no character appears twice? Give an integer.

**Answer:** 7

1. Keep a dictionary from each character to the index where it was last seen, and a left edge for the current stretch. When a character was last seen at or after the left edge, move the left edge to one past that index.
2. Reading with 0-based indexes: p, w give a stretch of 2. The second w at index 2 moves the left edge to 2. Then k, e extend it, and the next w at index 5 was last seen at 2, so the left edge moves to 3, leaving the stretch kew.
3. From index 3 the stretch kewabcd runs through index 9 and has length 7. The a at index 10 was last seen at 6, which is inside the stretch, so the left edge moves to 7.
4. The later stretches reach at most 7 as well: cdabxyz, which is 7 characters, ends where the second z at index 15 cuts it off. So the answer is 7. One pass with O(1) dictionary operations gives O(n).

**Problem 4.** The list is 100, 4, 200, 1, 3, 2, 101, 102, 5, 103, 104, 105, 7, 106, 3, 101, which repeats some values. What is the length of the longest run of consecutive integers, such as 4, 5, 6, that can be formed from values in the list? Order in the list does not matter, and a repeated value counts once. Give an integer.

**Answer:** 7

1. Put every value in a set, which removes repeats and makes the test "is v in the set" cost O(1) on average.
2. Start counting only from a value whose predecessor is not in the set, so that each run is walked once. The starts are 1 (0 is missing), 7 (6 is missing), 100 (99 is missing) and 200.
3. From 1 the run is 1, 2, 3, 4, 5 and stops because 6 is missing: length 5. From 7 the run is 7 alone. From 100 the run is 100, 101, 102, 103, 104, 105, 106 and stops because 107 is missing: length 7. From 200 the run is 1.
4. The longest is 7. Every value is visited at most twice in all, so the cost is O(n).

Every answer above is recomputed by a separate program when the site is built, and each is rebuilt by a different route from the written steps. A wrong answer would stop the build. Read [how the problems are checked](https://georgeliinternships.com/methodology.md).

These are our own practice problems, written for this site. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session.

## Build a complete map and mock interview study plan

Maps never appear in isolation during real hiring loops. Before scheduling mock rounds, make sure you are equally comfortable with the surrounding data structures that frequently partner with hash tables and tree maps:

- Arrays and strings for sliding windows, prefix sums, and in-place indexing.
- Linked lists for LRU/LFU cache node wiring and pointer cloning.
- Stacks and queues for monotonic next-greater lookups, parentheses parsing, and BFS levels.
- Trees, graphs, and heaps for ordered maps, shortest word paths, and top-K frequency extraction.

Structure every solo practice block like a live screen. Pick one problem from the easy, medium, or hard tiers above, start a countdown timer, and build a complete solution without checking hints or reference code. If you stall past your time box, study one solution carefully to understand the missing pattern, then immediately solve a fresh problem independently so you do not drift into passive reading.

Once your solo implementations run cleanly, practice explaining your choices aloud while tracing small inputs line by line. Speaking your complexity tradeoffs, collision assumptions, and edge cases turns silent problem-solving into clear communication. When you are ready for realistic pressure, run mock interviews with experienced software engineers who conduct technical loops regularly and can give direct feedback on pacing, clarity, and code cleanliness.

## Questions

### When should I use a hash map in a coding interview?

Use one when the problem repeats a question like "have I seen this value", "how many times did it occur" or "which items share this key". Each of those becomes a lookup instead of a scan of everything seen so far.

### What does a dict lookup cost in Python?

The Python documentation lists key lookup, insertion and deletion as O(1), and says that in the worst case, when every key hashes to the same value, each takes O(n). The O(1) figures are averages.

### What is the difference between a dict and a set here?

A set remembers only which values you have seen, and a dict remembers something about each one, such as a count or the position where it last appeared. Use a set when membership is all you need.

## How a session helps

A session with George is a place to code a problem aloud and have the reasoning questioned: why a dict and not a set, what the key is and what you assume about repeats. You write all the code yourself. Next, read the [data structures checklist](https://georgeliinternships.com/interview-prep/data-structures-checklist.md) and the [coding and complexity practice](https://georgeliinternships.com/interview-prep/coding-and-complexity-practice.md), and use the [coding prep schedule](https://georgeliinternships.com/tools/coding-prep-schedule.md) to put the topics on a calendar. See the [packages page](https://georgeliinternships.com/packages.md) for the sessions, or [book a session](https://georgeliinternships.com/book.md).

## Related

- [Internship interview prep](https://georgeliinternships.com/interview-prep.md)
- [Methodology and sources](https://georgeliinternships.com/methodology.md)
- [Internship role guides](https://georgeliinternships.com/roles.md)
