Patterns / Pattern 1 of 5
Hashing and counting
Remember what you have seen in a Map, so you never search for it twice.
The 30-second version
You're at a party and want to know whether two guests share a birthday. Instead of asking every pair of people, you carry a notebook. For each new guest, you check the notebook for their birthday, then write it down. One walk around the room is enough.
Hashing and counting, in three steps:
- Carry a notebook (in code, a Map or a Set).
- For each item, check the notebook first.
- Then write the item down, and move on to the next.
Think of it when a problem says:
- “find two that add up to…”
- “is there a repeat?”
- “count how many times…”
- “group the ones that are alike”
That’s the whole idea. The rest of this page shows it working, step by step.
Spot it when: You need to find a match, a duplicate, or count how often things appear.
In one line: Don't search for it. Remember it.
Words on this page, in plain English (21)Open if any word is new to you
- Variable
- A labelled box that holds a value. You give it a name, put something in it, and use the name later to get it back.
- String
- A piece of text, written between quotes. Each letter in it is a character.
- Boolean (true or false)
- A value that can only be
trueorfalse. Like a light switch: on or off. - Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
- If (a decision)
- Runs some code only when something is true. Like: if it's raining, take an umbrella.
- Loop
- Code that repeats. A
forloop repeats once per item or a set number of times; awhileloop repeats as long as something stays true. - Function
- A named, reusable recipe. You give it ingredients (inputs), it does its steps, and hands back a result.
- Return
- How a function hands back its answer. As soon as
returnruns, the function stops. - console.log
- Prints something so you can see it. The easiest way to find out what your code is really doing.
- Object
- A bundle of named values, in curly braces. Like a form with labelled boxes.
- Map
- A lookup table: it stores pairs of a key and a value, and finds any key instantly. Like a coat check: hand over a ticket, get your coat straight back.
- Set
- A collection that only remembers which things it has seen, with no repeats. Like a guest list: a name is either on it or not.
- Key
- The label you look something up by in a Map or object, like a word in a dictionary.
- Hash, hashing
- A quick calculation that turns a key into a shelf number, so a Map can jump straight to it instead of searching.
- Pattern
- A trick that solves a whole family of problems. Learn the trick once, and you can solve problems you've never seen.
- Template
- The usual shape of a pattern's code. You fill in the parts that change for each problem.
- Big O
- A way to say how much slower code gets as the input grows. It's about the trend, not exact seconds.
- O(1): constant time
- Takes the same time no matter how big the input is. Like opening a book at page 1.
- O(n): linear time
- The work grows in step with the input: twice the items, twice the work. One pass.
- O(n²): quadratic time
- Twice the items means four times the work. Usually a loop inside a loop. Fine for 100 items, painful for 100,000.
- Stack
- A pile where you only touch the top: add with
push, take withpop. The last thing in is the first out, like a pile of plates.
The slow part: searching
Most slow beginner solutions have the same problem hiding inside them: they search a list over and over. Asking "is 42 in this list?" means checking item after item until you find it. With 10 items that's nothing. With 100,000 items, asked 100,000 times, it's 10 billion checks, and your program will be stopped for taking too long.
Even list.includes(42) searches item by item. It's a loop in disguise.
The hashing pattern removes that search. Instead of looking for something, you remember it in a structure that can find it instantly.
Watch it work: spot the first repeat with a Set
fruit
seen (Set)
empty
- items looked at =
- 0
Start with an empty Set. It will remember every item we've looked at.
Meet the Map
A Map stores pairs: a key and its value. Think of a coat check: you hand over a coat (the value) and get a ticket number (the key). Later, the ticket gets your coat straight back, without anyone searching the whole room.
Try it: a Map of ages
const ages = new Map();
ages.set("Ana", 31); // store a key and its value
ages.set("Ben", 25);
console.log(ages.get("Ana")); // read a value by its key
console.log(ages.has("Ben")); // is this key stored?
console.log(ages.has("Cleo"));
console.log(ages.size); // how many keys
console.log(ages.get("Cleo")); // a missing key gives undefinedPress Run to see the output. You can change the code first.
The four things you'll use constantly:
| Code | What it does |
|---|---|
map.set(key, value) | Stores a value under a key (replacing any old one) |
map.get(key) | Reads the value, or undefined if the key isn't there |
map.has(key) | true if the key is stored |
map.size | How many keys are stored |
Meet the Set
A Set is a Map without values: it only remembers which things it has seen. Adding something twice has no effect.
Try it: a Set
const seen = new Set();
seen.add(7);
seen.add(3);
seen.add(7); // already there, nothing changes
console.log(seen.has(3));
console.log(seen.has(5));
console.log(seen.size);Press Run to see the output. You can change the code first.
Why it's instant
A Map doesn't keep keys in a line. It runs each key through a quick calculation, called a hash, that turns it into a shelf number. To find a key later, it runs the same calculation and goes straight to that shelf. That's where the pattern gets its name.
So has, get and set take about the same time whether the Map holds 10 keys or 10 million. In Big O terms, each one is O(1) on average, compared with O(n) for searching a list.
Race: how much work as the input grows?
Search the list every time O(n²)1,000,000 steps · 10 ms
Remember in a Map O(n)1,000 steps · instant
Times assume a fast computer doing about 100 million simple steps a second.
Template 1: remember as you go
Walk through the input once. For each item, first ask the Map or Set about it, then store it for the items that come later.
function solve(items) { const seen = new Set(); for (const item of items) { if (seen.has(/* what this item is looking for */)) { // found it: answer straight away } seen.add(item); } // got to the end without finding it}Use it for: "find two items that match", "has anything appeared before?".
Template 2: count, then answer
First count how many times each thing appears. Then use the counts to answer.
function countEach(items) { const counts = new Map(); for (const item of items) { counts.set(item, (counts.get(item) ?? 0) + 1); } return counts;}The line in the middle is worth learning by heart. counts.get(item) ?? 0 means "the count so far, or 0 if this is the first time", and then we add 1.
Try it: count the letters in a word
const counts = new Map();
for (const letter of "banana") {
counts.set(letter, (counts.get(letter) ?? 0) + 1);
}
console.log(counts);Press Run to see the output. You can change the code first.
Use it for: "do these two have the same contents?", "which item appears only once?", "what's most common?".
Template 3: group by a key
Put things that belong together under the same key. The trick is choosing a key that is the same for everything that belongs in a group.
function groupBy(items) { const groups = new Map(); for (const item of items) { const key = /* something every member of the group shares */; if (!groups.has(key)) groups.set(key, []); groups.get(key).push(item); } return [...groups.values()];}When to use it
Reach for a Map or Set when a problem asks you to:
- find a pair or match ("two numbers that add up to…"),
- spot duplicates or check if something was seen before,
- count how often things appear,
- group things that share something.
And whenever your first solution has a loop inside a loop where the inner loop is just searching, ask: could a Map remember this instead?
The cost
Hashing turns O(n²) solutions into O(n) ones, but nothing is free: the Map or Set uses extra memory, up to one entry per item (O(n) space). In almost every interview problem, that trade is well worth it.
Common mistakes
if (map.get(key))to check if a key exists. If the stored value is0,""orfalse, this says "no". Usemap.has(key).- Arrays as keys.
new Map().set([1, 2], "x").get([1, 2])givesundefined, because two arrays are never the same array, even with the same contents. Turn them into a string first, like"1,2". - Plain objects instead of Maps.
{}also stores keys and values, but turns every key into a string (so1and"1"collide) and has built-in keys like"constructor". AMaphas neither problem.
Learn it by heart
Understanding a pattern is the first half. The second is being able to write it without looking. Learn the recipe as words first, then each template in four steps. Your results go into your reviews, which bring each one back just before you’d forget it.
The recipe, out loud
- Make an empty
MaporSetbefore the loop. - For each item, first ask the Map about it (
hasorget). - Then store the item, so later items can find it.
- The Map answers instantly, so one pass is enough: O(n).
Remember as you go
Use it for: Have I seen this (or its partner) before?
Learn it by heart: Remember as you go
Read the 8 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function hasRepeat(items) { const seen = new Set(); for (const item of items) { if (seen.has(item)) return true; seen.add(item); } return false;}Count, then answer
Use it for: How often does each thing appear?
Learn it by heart: Count, then answer
Read the 7 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function countEach(items) { const counts = new Map(); for (const item of items) { counts.set(item, (counts.get(item) ?? 0) + 1); } return counts;}Group by a key
Use it for: Put things that share something into the same bucket.
Learn it by heart: Group by a key
Read the 9 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function groupByLength(words) { const groups = new Map(); for (const word of words) { const key = word.length; if (!groups.has(key)) groups.set(key, []); groups.get(key).push(word); } return [...groups.values()];}Practice problems
Easiest first. Each has hints and a full walkthrough.
| Solved | Problem | Difficulty |
|---|---|---|
| Pair to target | easy | |
| Spot a repeat | easy | |
| Letter twins | easy | |
| First lonely letter | easy | |
| Group the twins | medium | |
| Longest run | medium |
More patterns
- Two pointers
Walk through a list from both ends (or at two speeds) at once.
- Sliding window
Keep a stretch of the list and slide it along instead of starting over.
- Binary search
Halve the search space with every guess.
- Stack
Keep the most recent unfinished thing on top, and finish it first.
New to coding? Start with the JavaScript basics, or browse every practice problem.