Skip to main content

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.

beginner

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

ToolReach for it when...
CounterAnagram check, frequency map, most-common element
defaultdictBuilding adjacency lists, grouping items
dequeBFS queue, sliding window with O(1) left-pop
heapqTop-K, merge-K sorted lists, running median
bisectSearch in sorted array, count elements in range
functools.cacheDP with overlapping subproblems

When Not to Reach for Them

Each tool has a failure mode, and reaching for it reflexively is its own bug:

  • deque only beats a list when you touch the left end. For a plain right-side stack, a list is just as fast and more familiar.
  • heapq wins when you pull elements off incrementally; if you need the data fully sorted once, sorted() is simpler at the same cost.
  • functools.cache is 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).
  • Counter does a full O(n) tally; to answer "is there any duplicate?", a set with an early return stops as soon as it finds one.

Related Concepts

beginner

Hashing & Frequency Maps

The pattern behind a huge share of array and string problems: use a hash map to trade memory for speed, turning O(n²) searches into O(n) single-pass solutions.

beginner

Big-O & Complexity

A mental model for reasoning about how an algorithm's time and memory usage scale with input size — the foundation of every performance conversation in engineering.