Chapter 02 - Hash Maps and Hash Sets
When we keep asking “have I already seen this value?”, a hash map or a hash set answers in constant time.
This page is the entry point of chapter 2 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.
The idea
We trade memory for time. Instead of scanning the array again for every element, we remember what we have seen in a structure with \(O(1)\) average lookup. For the unsorted pair sum, we store each number and look for its complement. A set answers membership questions; a map also stores something about each key: a count, an index, a list.
When to reach for it
- We need to know if a value was already seen, or how many times.
- The input is unsorted and sorting it would cost \(O(n \log n)\) or destroy the original indexes.
- We must detect duplicates, group items, or check constraints row by row (Sudoku).
In Rust
*map.entry(key).or_insert(0) += 1counts occurrences in one line.HashSet::insertreturnsfalsewhen the value is already there: a free duplicate check.- Keys must implement
HashandEq, sof64cannot be a key. And the iteration order is not deterministic: sort the output before comparing it in a test.
Problems in this chapter
- p032 - Pair Sum - Unsorted: Pair Sum - Unsorted (Hash Maps and Hash Sets) solved in Rust: in an unsorted array, find a pair of numbers that add up to a target, using a HashMap.
- p035 - Verify Sudoku Board: Verify Sudoku Board (Hash Maps And Hash Sets), solved in Rust. Given a partially completed 9x9 Sudoku board, validate it.
- p040 - Zero stripping: Zero stripping (Hash Maps And Hash Sets), solved in Rust. For each 0 in an m x n matrix, set its entire row and col to 0 in place.
- bonus016 - Longest Chain of Consecutive Numbers: Longest Chain of Consecutive Numbers (Hash Maps And Hash Sets), solved in Rust. Find the longest chain of consecutive numbers in an array. Two numbers are…
- bonus020 - Geometric Sequence Triplets: Geometric Sequence Triplets (Hash Maps And Hash Sets), solved in Rust. A geometric sequence triplet is a sequence of three numbers where each successive…
Other chapters
All the chapters, with every problem, are listed on the series page.