Hashing: counting with an array, then with a map
1 The same question, many times
A teacher marks a short quiz out of 5. Seven students score marks = [2, 5, 2, 0, 3, 2, 5]. Then the teacher asks a few questions about the class. How many students scored 2? How many scored 4? How many scored 5?
Each question asks how many times one value appears. For 2 the answer is 3, for 4 it is 0, and for 5 it is 2.
The direct way answers each question with its own walk through the array:
for each query x:
found = 0
for each mark in marks:
if mark == x:
found = found + 1
answer found
One walk takes n steps, and there are q questions, so this is O(n · q). With 10⁵ marks and 10⁵ questions, that is around 10¹⁰ steps. At about 10⁸ steps a second it is far past the time limit, so it gets Time Limit Exceeded (TLE).
Every walk reads the same marks again. We can do that reading once.
2 Count once, then look up
We walk through the array once, before any question, and count every value on the way. After that, each question is a single lookup.
The marks go from 0 to 5, so an array of six slots can hold every count. Slot v holds how many students scored v. This is a count array, also called a frequency array. The value itself is the index.
Keeping a count at a place picked by the key itself is the simplest form of hashing. Here the key is a small number, so it can be the index as it is.
- Building the counts: n steps. For each mark, we add 1 to its slot.
- Answering: one step per question. The answer for x is
count[x].
The total is O(n + q). At 10⁵ and 10⁵, that is about 2 × 10⁵ steps, far inside the limit.
3 Building the count array, step by step
All six slots start at 0. We read the marks from left to right and add 1 to the slot that each mark names.
| Step | i | marks[i] | Slot that gets +1 | count after |
|---|---|---|---|---|
| 1 | 0 | 2 | 2 | [0, 0, 1, 0, 0, 0] |
| 2 | 1 | 5 | 5 | [0, 0, 1, 0, 0, 1] |
| 3 | 2 | 2 | 2 | [0, 0, 2, 0, 0, 1] |
| 4 | 3 | 0 | 0 | [1, 0, 2, 0, 0, 1] |
| 5 | 4 | 3 | 3 | [1, 0, 2, 1, 0, 1] |
| 6 | 5 | 2 | 2 | [1, 0, 3, 1, 0, 1] |
| 7 | 6 | 5 | 5 | [1, 0, 3, 1, 0, 2] |
After the last step, count is [1, 0, 3, 1, 0, 2]. The three questions read slots 2, 4 and 5, and get 3, 0 and 2. Nobody scored 4, so slot 4 stays 0, and 0 is the right answer.
The slots add up to 7, one for each student. That is a quick check on any count array.
In code, countMarks builds the counts first, then answers each query from them:
For queries = [2, 4, 5], it returns [3, 0, 2].
4 Letters as indexes
Letters work the same way once we turn each one into a number. The letters 'a' to 'z' have codes that follow each other. So c − 'a' is 0 for 'a', 1 for 'b', and 25 for 'z', and 26 slots count every letter of a word.
For "banana", slot 0 ('a') holds 3, slot 1 ('b') holds 1, and slot 13 ('n') holds 2. Only the way to get a letter's code differs between languages.
C++
A character is a number. c - 'a' works as written.
A character is a number. c - 'a' works as written.
A character is a number. c - 'a' works as written.
ord. ord(c) gives the code, so we write ord(c) - ord('a').
charCodeAt. c.charCodeAt(0) gives the code.
Bytes. word[i] gives each letter's code as a byte.
Bytes. bytes() gives each letter's code. It then needs as usize to be used as an index.
5 When an array will not do
A count array needs keys that are whole numbers in a small range, known in advance. Three kinds of input break it:
- Large values. With values up to 10⁹, the array needs 10⁹ slots. That is about 4 GB, far more memory than a program gets, even if only five values ever appear.
- Negative values. A value of −3 has no slot.
count[-3]reads memory outside the array and quietly gives a wrong answer. - Keys that are not numbers. Words and names have no index at all.
A shift fixes a small negative range. With values from −100 to 100, slot v + 100 holds the count of v, and 201 slots are enough. Nothing like that works for 10⁹ or for words.
For these, we count in a hash map from each key to its count. It keeps an entry only for the keys that appear. It also turns any key into a place to store its count, and the next lesson shows how.
6 Counting with a map
Six students vote for a team colour. The keys are words, so we count them in a map countOf.
The loop is the same as with the array. For each vote, we read its count, with 0 for a key not yet in the map, and store one more.
| Vote | countOf after |
|---|---|
| red | red 1 |
| blue | red 1, blue 1 |
| red | red 2, blue 1 |
| green | red 2, blue 1, green 1 |
| red | red 3, blue 1, green 1 |
| blue | red 3, blue 2, green 1 |
Next, we want the most voted and the least voted colour. We go over the map once and keep the best count so far, with its key, at both ends:
- Most voted.
mostCountstarts at 0. Any count above it takes its place. - Least voted.
leastCountstarts at n + 1, above any count a key can have. Any count below it takes its place.
It returns red with 3 votes and green with 1, as ["red", "green"].
The second loop goes over the map, not over the votes. The map has one entry per different key, so this loop takes at most n steps, and usually far fewer.
7 Array or map
Both count each value in about one step. They differ in which keys they accept and how much one step costs.
| Count array | Hash map | Sorted map | |
|---|---|---|---|
| Keys | whole numbers in a small range | any key | any key with an order |
| One update or lookup | one array read | about one step, a few times slower | about log n steps, around 17 at 10⁵ |
| Memory | one slot per possible value | one entry per key that appears | one entry per key that appears |
| Keys come out | in order of value | in no fixed order | in sorted order |
- Count array: the fastest, but its size comes from the range, not from n. It needs a slot for every value that could appear, even the ones that never do. 10⁵ marks from 0 to 100 need 101 slots. 10⁵ values up to 10¹⁸ would need 10¹⁸ slots, far more memory than any computer has, and all but 10⁵ of them would stay 0. So we use it only when the constraints give a small range, such as marks from 0 to 100 or the 26 lowercase letters.
- Hash map: the default for everything else. It keeps one entry per value that appears, so 10⁵ values take about 10⁵ entries, whatever their range. Large values, negative values and words all fit.
- Sorted map: when order matters. For example, printing each value with its count from smallest to largest. The standard library lesson lists it in each language.
At n = 10⁵, all three finish well inside the time limit. The next lesson shows what a hash map does in each step, and why it costs more than an array read.
8 Mistakes, and when to count
- An array one slot short. Marks from 0 to 5 need 6 slots, not 5. With 5 slots, a mark of 5 is a Runtime Error in most languages, and a quiet wrong answer in C++ and JavaScript.
- The least count starting at 0. No count is below 0, so
leastnever changes and comes back empty. Start above any possible count, as n + 1 does. - Ties. With
votes = ["red", "blue"], both colours have 1 vote. Most maps promise no order, so the winner depends on which key the loop meets first. A problem with ties states a rule, such as "the smaller value wins", and the comparison must apply it.
This subtopic's problems all ask how often each value appears. Words like "frequency", "how many times", "most frequent" or "count of each" point to them. Then the value range picks the tool: a small range means an array, and anything else means a map.
The habit to keep: when a problem asks "how many times", read the value range before writing code. It tells us whether an array is enough or we need a map.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.