Hashing Fundamentals
What is this?
This is where you learn the three everyday jobs a hash structure does. Use a set to check "have I seen this before?", a Counter to answer "how many of each do I have?", and a canonical key to lump together things that are secretly the same (like words that are anagrams). Each one replaces a slow, item-by-item comparison with one quick pass.
๐ก Fun fact: The "group things that are secretly the same" trick has a famous twist โ to detect anagrams you can multiply a prime number per letter, since every word maps to a unique product. This is essentially the Fundamental Theorem of Arithmetic, a 2000-year-old idea from Euclid, repurposed as a hash key.
๐ The 5 problems in this chapter are free. Sign in with Google or Microsoft to start solving.
Core idea: Before the clever "what to store" tricks, master the three everyday uses of a hash structure: a set to test distinctness, a Counter to tally "how many of each", and a canonical key to group items that are secretly the same. Each turns an O(nยฒ) scan into one O(n) pass.
The three reflexes
| Reflex | Trigger phrase | Tool |
|---|---|---|
| Set | "distinct / unique / seen" | set() |
| Frequency | "how many of each / most common / counts" | collections.Counter |
| Canonical key | "group the ones that are the same under โฆ" | dict keyed by a normalized form |
The five problems
- Distribute Candies โ a set gives the distinct-type count; answer
min(distinct, n//2). - Minimum Steps to Make Anagram โ subtract two frequency tables; the deficit is the answer.
- Bulls and Cows โ bulls by position, then count the leftover digits and sum
minof the two tallies for cows. - Longest Harmonious Subsequence โ count values; for each
v, combinecount[v] + count[v+1]. - Group Shifted Strings โ build a canonical key (mod-26 difference tuple) and group by it.
The pattern
Counting collapses "compare every element to every other" into "tally once, then read the tallies." A set answers membership in O(1). And when items are equivalent under some transformation (a shift, a sort, a rotation), compute a canonical form and let the map group them โ the same trick behind Group Anagrams.
๐ Draw it yourself
- Two tally tables. For Bulls and Cows or the anagram problem, draw both frequency tables and read the answer off the per-letter differences.
- Canonical key. For Group Shifted Strings, write a few strings and their difference-tuple keys; watch equivalent ones land in the same bucket.
Snap photos and embed them with the /host-diagrams skill.
Key takeaways
- Three reflexes: set (distinct), Counter (how many), canonical key (group equivalents).
- Counting beats nested comparison โ tally once in O(n), then answer questions off the tallies.
- A canonical key turns "are these equivalent?" into "do they hash the same?"
- Why it matters: these are the bread-and-butter hash moves every harder problem composes from.
Order: Distribute Candies โ Min Steps to Make Anagram โ Bulls and Cows โ Longest Harmonious Subsequence โ Group Shifted Strings.
Core idea: Two strings belong together when one is a uniform letter-shift of the other (every character moved by the same amount mod 26). That relationship is captured exactly by the tuple of consecutive differences
(s[i] - s[i-1]) mod 26โ a canonical key that is identical for every string in the same shifting family. Compute that key, drop each string into a dictionary bucket, done.
Problem, rephrased
Imagine you maintain a Caesar-cipher message archive. Operators encode short words by rotating every letter forward by some secret offset: with offset +1, "abc" becomes "bcd"; with offset +23, it becomes "xyz" (aโx, bโy, cโz, wrapping around the alphabet). Crucially the whole word uses one offset, so the shape of the word โ how each letter steps relative to the one before it โ never changes. "abc", "bcd", and "xyz" are the same message under three different rotations.
You're handed a pile of lowercase strings. Group together all strings that are rotations of one another. Return the groups in any order, and the strings within each group in any order.
A string t is a shift of s when they're the same length and there's a single offset k such that t[i] = (s[i] + k) mod 26 for every position i. Wrap-around counts: "az" shifted by +1 is "ba" (aโb, zโa), so "az" and "ba" are in the same group.
Input (strings) |
Output (groups, any order) | Why |
|---|---|---|
["abc", "bcd", "acef"] |
[["abc","bcd"], ["acef"]] |
abcโbcd is +1; acef has a different step shape |
["az", "ba"] |
[["az","ba"]] |
az shifted +1 wraps to ba |
["a", "z", "x"] |
[["a","z","x"]] |
single characters are all shifts of each other |
Sign in to continue reading
The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.
Sign in to read the full lesson