implementation
Python Speed Kit
The standard-library tools that replace hand-rolled data structures: Counter, defaultdict, deque, heapq, bisect, and functools.cache — what each does, when to reach for it, and when not to.
Why This Kit Matters
Real problems rarely require inventing new data structures — they require reaching for the right standard-library tool and using it correctly. Each of these six replaces a chunk of error-prone hand-rolled code (a manual count, a hand-built heap, a from-scratch memo table) with one well-tested call. Knowing them is the difference between writing the data structure and writing the solution.
The Six Tools
collections.Counter — frequency map in one call.
collections.defaultdict — dict that never raises KeyError.
collections.deque — O(1) append and pop from both ends (BFS, sliding window).
heapq — min-heap on a plain list; negate values for max-heap.
bisect — binary search on a sorted list in one line.
functools.cache — memoize any pure function automatically.
Canonical Use Cases
| Tool | Reach for it when... |
|---|---|
| Counter | Anagram check, frequency map, most-common element |
| defaultdict | Building adjacency lists, grouping items |
| deque | BFS queue, sliding window with O(1) left-pop |
| heapq | Top-K, merge-K sorted lists, running median |
| bisect | Search in sorted array, count elements in range |
| functools.cache | DP with overlapping subproblems |
When Not to Reach for Them
Each tool has a failure mode, and reaching for it reflexively is its own bug:
dequeonly beats alistwhen you touch the left end. For a plain right-side stack, alistis just as fast and more familiar.heapqwins when you pull elements off incrementally; if you need the data fully sorted once,sorted()is simpler at the same cost.functools.cacheis unbounded — a slow memory leak in any long-running process, and silently wrong on a function whose result depends on anything other than its arguments. Bound it with@lru_cache(maxsize=N).Counterdoes a full O(n) tally; to answer "is there any duplicate?", asetwith an early return stops as soon as it finds one.