Lessons · TypeScript · look it up in a Map
Remember what you have seen, in a Map
Walk the data once; store each thing you see in a Map (or object) keyed by what you will later need to look up.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Pairs that sum, duplicates, grouping, matching records, counting: one pattern, dozens of interview and real-world problems.
How to think about it
Ask: standing at item i, what would I need to know about earlier items to answer right now? Store exactly that, keyed so the lookup is one step.
Worked example
const seen = new Map();value -> first index.
for (let i = 0; i < nums.length; i++) {One pass.if (seen.has(nums[i])) return [seen.get(nums[i]), i];Instant check against everything earlier.
seen.set(nums[i], i);Remember for later.
}
Your turn
Count words with an object.
const counts = {};
for (const w of words) counts[w] = (counts[w] 0) + 1;Solve one with the tests running
The trap
Using an object when keys might be numbers or objects: object keys become strings. Map keeps keys as they are.
Practise look it up in a Map on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.