Choose the structure for the operation
Pick a data structure from the operations a class must make fast.
List the hot operations first
Before choosing an array or a map, write down the operations that run most and how fast they must be. "Find by id" wants a hash map. "Give me the next due job" wants a heap. "Items in insertion order" wants a list or an ordered map.
A design that searches an array on every request works in a demo and falls over with real data. The hidden tests check this with large inputs.
Common pairings
Map: lookup by key in constant time. Set: membership checks. Heap: smallest or largest next, in log time. Sorted array: range queries with binary search. Two structures together are normal when two operations must both be fast.
Key takeaways
- Start from the operations, not the structure.
- Lookup by key: map. Next by priority: heap.
- Combine structures when two operations must both be fast.
Hands-on coding exercise
Count unique visitors to a page. visit(userId) may be called many times for the same person; count() is the number of different people.
Pick the structure that makes "have I seen this id?" instant.
class VisitorCounter {
visit(userId: string): void {
throw new Error("Not implemented");
}
hasVisited(userId: string): boolean {
throw new Error("Not implemented");
}
count(): number {
throw new Error("Not implemented");
}
}
Run your solution against 4 automated tests in the interactive workspace:
Check your understanding
Answer these questions interactively to test what you learned and track progress on your skill map:
- A scheduler must always find the job due soonest. Which structure fits best?
- You need to check "have we seen this URL?" millions of times. What fits?