Lesson 2 · Unit 04
Counting with a map
The frequency-map idiom, in one pass
What you practise
- The frequency-map idiom
- First unique character
- Most common item
Try a question from this lesson
Pick one
How does counting the items of a list of n entries with a hash map grow?
Correct answer
O(n): one pass, O(1) work per item
Why
Each item costs one lookup and one store, both O(1) on average, and there are n items. No item is ever compared with another, and a hash map does not sort anything.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The counting idiom
To count everything in one pass, keep a map from item to count. For each item: read its current count (0 if it is missing), add one, store it back.
counts = {}
for v in ["tea", "milk", "tea"]:
counts[v] = counts.get(v, 0) + 1
print(counts["tea"]) # 2const counts = new Map();
for (const v of ["tea", "milk", "tea"]) {
counts.set(v, (counts.get(v) ?? 0) + 1);
}
console.log(counts.get("tea")); // 2const counts = new Map<string, number>();
for (const v of ["tea", "milk", "tea"]) {
counts.set(v, (counts.get(v) ?? 0) + 1);
}
console.log(counts.get("tea")); // 2Python notecollections.Counter(votes) runs this whole loop for you, and defaultdict(int) lets you write counts[v] += 1.
JavaScript note?? means "use the right side when the left is null or undefined". It supplies the 0 for an item seen for the first time.
TypeScript noteWithout <string, number> an empty new Map() is a Map<any, any>, and nothing you put in it is checked.
10 more exercises in the app
- 3× type the answer
- 2× fill the blanks
- 1× order the lines
- 2× multiple choice
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.