A2Z Lesson

Log in
← Back to the A2Z sheet

Step 01 Beginner Problems — Standard Libraries & Collections

Python Libraries Part 2

Medium

Part 2 is the DSA power toolkit: the collections module (Counter, defaultdict, deque), heapq for priority queues, bisect for sorted data, and itertools for combinations and prefix work. These four modules convert whole categories of medium problems into a few lines — frequency questions, top-K questions, sliding windows and sorted-insertion questions all have a dedicated tool here.

collections.Counter and defaultdict

Counter is a dict specialised for counting hashable items: Counter(nums) builds the whole frequency table in one call. Its methods do the rest — most_common(k) returns the k most frequent (value, count) pairs, and arithmetic like c1 - c2 discards non-positive counts, which makes anagram comparison a two-liner. Missing keys read as 0 instead of raising.

defaultdict(list) / defaultdict(int) creates values on first access, removing the 'if key not in d' ceremony when grouping items or accumulating counts by hand.

from collections import Counter freq = Counter([1, 2, 2, 3, 3, 3]) print(freq.most_common(1)) # [(3, 3)] print(freq[2]) # 2 print(Counter('aab') == Counter('aba')) # True -> anagram check

collections.deque: the double-ended queue

A deque (deck) supports O(1) append/pop at BOTH ends — append, appendleft, pop, popleft — where a list pays O(n) at the front. That single fact makes deque the correct tool for queues (BFS level order), sliding-window problems that evict from the left, and monotonic-queue patterns later in this sheet. rotate(k) shifts elements cyclically, a neat trick for rotation problems. If your solution calls pop(0) or insert(0, ...) on a list in a loop, switch it to a deque and the hidden O(n^2) disappears.

heapq: priority queues in a list

heapq turns a plain list into a min-heap: heapify in O(n), heappush/heappop in O(log n), and heap[0] peeks the smallest in O(1). Python has no max-heap — negate values on the way in and out, or store tuples (-priority, item). Two idioms matter: top-K largest = keep a heap of size K, pushing each item and popping the smallest when the heap exceeds K (the heap then holds exactly the K best); and nlargest(k, iterable) / nsmallest for one-shot answers. Heap entries that are tuples compare element by element — include a tiebreaker (like an index) so Python never tries to compare your payload objects.

import heapq def top_k(nums, k): heap = [] for x in nums: heapq.heappush(heap, x) if len(heap) > k: heapq.heappop(heap) return sorted(heap, reverse=True) print(top_k([3, 1, 5, 2, 4], 2)) # [5, 4]

bisect: binary search on sorted lists

bisect works on any sorted list: bisect_left(a, x) is the first index where x could insert keeping order (equivalently, the count of elements < x); bisect_right(a, x) counts elements ≤ x. Their difference is the frequency of x — a complete occurrence counter in O(log n). insort inserts in O(n) because of shifting, so bisect shines for queries, not for building. Whenever you hand-write a binary search for bounds in Python, check whether bisect already says it in one word.

itertools: combinatorics and prefix tools

itertools generates iterator building blocks: permutations and combinations (and combinations_with_replacement) for brute-force and backtracking practice; product for Cartesian products (nested loops as data); accumulate for running totals — accumulate(nums) is the prefix-sum array in one call; groupby for collapsing consecutive runs (run-length encoding problems); and chain to iterate several sequences as one. All are lazy generators, so they stream instead of materialising huge lists in memory.

Choosing the tool (text summary): Counting things -> Counter Both-ends queue -> deque Repeatedly need the smallest/largest -> heapq Queries on sorted data -> bisect Generate combos/permutations/prefix sums -> itertools

Key points

  • Counter builds frequency tables in one call; most_common(k) answers most 'top frequency' questions directly.
  • deque gives O(1) at both ends — any pop(0)/insert(0) loop on a list is an accidental O(n^2) waiting to be fixed.
  • heapq is a min-heap (negate for max); top-K = a heap capped at size K.
  • bisect_left/bisect_right on sorted data give insertion points and occurrence counts in O(log n).
  • itertools.accumulate is prefix sums in one call; permutations/combinations power brute-force practice.
  • Match the tool to the problem shape: counting→Counter, queue→deque, extremes→heapq, sorted queries→bisect.

Suggested questions

Highest Occurring Element in an Array ↗ Counter(...).most_common(1) is this problem in one line — then also write the manual version.
Sort Characters by Frequency ↗ Counter plus sorting items by count descending; a Part 2 showcase problem.
Sum of Highest and Lowest Frequency ↗ max(freq.values()) and min(freq.values()) once the Counter exists.
Basic Hashing The concept lesson under Counter: what hashing is and why it averages O(1).

Source note: this lesson follows the structure of Striver's public A2Z DSA course (takeUforward). Each problem links to its original platform, and all problems and content belong to their respective owners — STUDY-BUDDY does not claim ownership of the sheet or its problems, and no permission beyond public linking is claimed.