Strings, hashing and frequency counting
Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.
What you will be able to do
#- Use a hash map to count frequencies in O(n) time.
- Explain average O(1) lookup and what causes collisions.
- Decide when a hash map beats sorting for a comparison task.
Overview
#Strings are sequences
A string is a sequence of characters. Indexing and iteration behave like an array of characters, but strings are usually immutable, so building a result means appending to a new structure.
Hash maps turn search into lookup
A hash map stores key-value pairs. It hashes the key to a bucket and reads or writes there. On average that is O(1) per operation, which is why counting frequencies is O(n):
function charCounts(s) {
const counts = new Map();
for (const ch of s) {
counts.set(ch, (counts.get(ch) || 0) + 1);
}
return counts;
}
Anagram check
Two strings are anagrams when their frequency maps match:
function isAnagram(a, b) {
if (a.length !== b.length) return false;
const counts = new Map();
for (const ch of a) counts.set(ch, (counts.get(ch) || 0) + 1);
for (const ch of b) {
const c = counts.get(ch);
if (!c) return false;
counts.set(ch, c - 1);
}
return true;
}
This is O(n) time and O(k) space where k is the number of distinct characters.
Collisions and the worst case
When two keys hash to the same bucket, the map must resolve the clash, usually by chaining or probing. In the worst case many keys collide and lookup degrades to O(n). Good hash functions make this rare, so we quote the average case as O(1) and note the worst case honestly.
Hash map or sort
Sorting also groups equal elements, but it costs O(n log n). A hash map is usually faster for counting and membership. Sorting wins when you need the elements in order anyway, or when you cannot hash the keys.
Practice next
- Group a list of words into anagram buckets using a canonical key.
- Find the k most frequent elements using a frequency map.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does charCounts('aab') return, described as key-value pairs?
starter.javascriptconst counts = new Map(); for (const ch of 'aab') counts.set(ch, (counts.get(ch) || 0) + 1);Reveal the reference answer
reference.javascripta appears twice and b once, so the map is a -> 2, b -> 1.Authored expected output: a -> 2, b -> 1
The get-or-zero idiom increments existing counts and initialises new ones.
Exercise 2Predict
Are 'listen' and 'silent' anagrams?
starter.javascript// compare frequency maps of both stringsReveal the reference answer
reference.javascriptBoth contain l, i, s, t, e, n exactly once, so the frequency maps match and they are anagrams.Authored expected output: true
Equal frequency maps are the definition of an anagram.
Exercise 3Explain
Explain the difference between the average and worst case for hash map lookup.
Reveal the reference answer
reference.textOn average a good hash function spreads keys evenly, so each lookup touches a constant number of entries, giving O(1). In the worst case many keys collide into the same bucket, so the map must scan them, giving O(n). The average case is what we usually quote, but the worst case is real and can be triggered by adversarial input.Authored expected output: Average O(1) from even spreading; worst O(n) when many keys collide.
Naming both cases is more honest than claiming constant time unconditionally.
Common misconceptions
#- Hash lookup is always O(1). It is O(1) on average; adversarial or unlucky collisions can make it O(n).
- A hash map keeps keys in order. It does not; use a sorted structure if order matters.
- Two different keys can never share a bucket. Collisions are normal and must be handled.
Follow-up practice
#- dsa-from-zero-stacks-and-queues
- dsa-from-zero-heaps-and-priority-queues
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.