PDSA Interactive Book
Practice tool

Pattern playbook

Fifteen patterns cover most interview and contest problems. Learn to spot the signal, then reach for the matching tool — every example below runs.

Most interview and contest problems are one of about fifteen patterns wearing a disguise. The skill is to recognise the signals in the statement, pick the pattern, and then fill in the details. Each card below gives the signals, the one-paragraph idea, a worked example that really runs (press ▶ to try it or edit it), the cost, and LeetCode problems that use the same pattern.

Which pattern? Match the signal

If the problem says…Reach for
sorted input, pair/triple wantedTwo pointers
longest / shortest contiguous blockSliding window
many range sums, or 'subarrays with sum k'Prefix sums + hash map
'seen before?', counts, duplicatesHash map / set
next greater / smaller, spansMonotonic stack
'minimum possible maximum', yes/no check is monotoneBinary search on the answer
overlapping intervals / schedulesSort, then sweep
fewest steps in an unweighted graph or gridBFS
regions, reachability, prerequisitesDFS / topological order
k best, repeated min or maxHeap
merging groups, redundant edgeUnion-Find
generate every arrangement, n ≤ 20Backtracking
count ways, min cost, overlapping sub-problemsDynamic programming
local choice provably safeGreedy
weighted edges, non-negativeDijkstra
A routine that works

1) Write the brute force and its cost. 2) Ask what the brute force repeats or wastes. 3) Match that waste to a pattern. 4) State the new cost before you code. 5) Test on the smallest case, an empty input and a tricky one.

The 15 patterns

Two pointers Week 2

Signals
  • sorted array or string
  • find a pair / triple with a property
  • reverse, partition or compare from both ends
Idea

Keep one index at each end (or one slow, one fast). Each step moves one pointer inward using what the sorted order tells you, so you never need a nested loop.

Cost: O(n) time, O(1) space

Python · editable
Expected output: (4, 6) None

Practise: Two Sum II ↗ · Container With Most Water ↗ · Valid Palindrome ↗ · Move Zeroes ↗

Sliding window Week 3

Signals
  • contiguous subarray / substring
  • 'longest', 'shortest' or 'best sum of size k'
  • a condition that can be maintained while the window grows and shrinks
Idea

Grow the window on the right; when the condition breaks, shrink from the left. Each element enters once and leaves once, so the total is linear.

Cost: O(n) time, O(window) space

Python · editable
Expected output: 3 1 3

Practise: Longest Substring Without Repeating ↗ · Minimum Size Subarray Sum ↗ · Max Average Subarray I ↗

Prefix sums Week 3

Signals
  • many range-sum queries
  • 'number of subarrays with sum k'
  • counting between two positions
Idea

Precompute P[i] = a[0] + … + a[i−1]. Then any range sum is P[j] − P[i] in O(1). Combine with a hash map of earlier prefix values to count subarrays with a target sum.

Cost: O(n) build, O(1) per query

Python · editable
Expected output: 2 5

Practise: Subarray Sum Equals K ↗ · Range Sum Query ↗ · Product of Array Except Self ↗

Hash map: count and complement Week 3

Signals
  • 'have I seen this before?'
  • frequencies, duplicates, anagrams
  • find a partner value: target − x
Idea

A dict or set turns an O(n) search into an O(1) lookup. Store what you have seen; look up what you need. Check for the complement BEFORE inserting the current item.

Cost: O(n) time, O(n) space

Python · editable
Expected output: [0, 1] [('i', 4), ('s', 4)]

Practise: Two Sum ↗ · Group Anagrams ↗ · Contains Duplicate ↗ · Longest Consecutive Sequence ↗

Monotonic stack Week 3

Signals
  • 'next greater / smaller element'
  • 'how many days until warmer'
  • largest rectangle, spans
Idea

Keep a stack whose values are in sorted order. When a new value breaks the order, pop everything it beats — each popped item has just found its answer. Every item is pushed and popped once.

Cost: O(n) time, O(n) space

Python · editable
Expected output: [5, 25, 25, -1, 8, -1]

Practise: Daily Temperatures ↗ · Next Greater Element I ↗ · Largest Rectangle in Histogram ↗ · Valid Parentheses ↗

Binary search on the answer Week 2

Signals
  • 'minimum possible maximum' / 'smallest x such that…'
  • a yes/no check that is monotone: if x works, x+1 works
  • the answer lies in a numeric range
Idea

Do not search an array — search the range of possible answers. Write a function ok(x) that tests feasibility in O(n), then binary-search the smallest x with ok(x) true.

Cost: O(n log range)

Python · editable
Expected output: 4 30

Practise: Koko Eating Bananas ↗ · Binary Search ↗ · Ship Packages in D Days ↗ · Search in Rotated Sorted Array ↗

Sort, then sweep (intervals) Week 7

Signals
  • overlapping intervals, meetings, schedules
  • merge / count rooms / remove overlaps
  • greedy choice needs an order
Idea

Sort by start (to merge) or by finish time (to pick the most non-overlapping). After sorting, one left-to-right pass is enough because only neighbours can interact.

Cost: O(n log n) for the sort, O(n) sweep

Python · editable
Expected output: [[1, 6], [8, 10], [15, 18]] 3

Practise: Merge Intervals ↗ · Non-overlapping Intervals ↗ · Meeting Rooms II (premium) ↗

BFS: shortest path, levels, grids Week 4

Signals
  • fewest steps / moves / edges
  • unweighted graph or grid
  • level-by-level processing
Idea

A queue explores vertices in order of distance. The first time you reach a vertex is the shortest way. Mark vertices visited when you ENQUEUE them, not when you pop them.

Cost: O(n + m)

Python · editable
Expected output: 4

Practise: Shortest Path in Binary Matrix ↗ · Rotting Oranges ↗ · Word Ladder ↗ · Level Order Traversal ↗

DFS: components, cycles, topological order Week 4

Signals
  • connected regions, islands, reachability
  • dependencies / prerequisites
  • any 'explore everything reachable' task
Idea

Recurse into each unvisited neighbour. Count how many times you START a fresh search to count components. For directed graphs, an edge back to a vertex still on the stack means a cycle.

Cost: O(n + m)

Python · editable
Expected output: 3

Practise: Number of Islands ↗ · Course Schedule ↗ · Number of Provinces ↗ · Clone Graph ↗

Heap / top-k Week 6

Signals
  • 'k largest / smallest / most frequent'
  • repeatedly need the current min or max
  • merge k sorted lists, running median
Idea

A heap of size k keeps the best k items in O(log k) per element. Python's heapq is a MIN-heap: for the k largest, keep a min-heap of size k and drop the smallest when it overflows.

Cost: O(n log k)

Python · editable
Expected output: 5 4 [9, 7, 5]

Practise: Kth Largest Element ↗ · Top K Frequent Elements ↗ · Merge k Sorted Lists ↗ · Median from Data Stream ↗

Union-Find Week 6

Signals
  • 'are these connected?' while edges keep arriving
  • group merging, redundant edge, number of components
  • Kruskal's MST
Idea

Each group has one representative. find follows parents to the root (compress the path as you go); union links the two roots. Union by size keeps trees shallow.

Cost: almost O(1) amortised per operation

Python · editable
Expected output: [True, True, False, True]

Practise: Redundant Connection ↗ · Connected Components (premium) ↗ · Accounts Merge ↗

Backtracking Recursion chapter

Signals
  • generate all subsets / permutations / combinations
  • 'place things so that no rule is broken' (N-Queens, Sudoku)
  • small input size (n ≤ 20)
Idea

Build the answer one choice at a time: choose → explore → un-choose. Prune a branch as soon as it cannot lead to a valid answer. See the Recursion & Backtracking chapter for the full treatment.

Cost: exponential in the worst case; pruning is what makes it usable

Python · editable
Expected output: [[2, 3, 6], [3, 8], [5, 6]]

Practise: Subsets ↗ · Permutations ↗ · Combination Sum ↗ · N-Queens ↗

Dynamic programming Week 9

Signals
  • 'count the ways', 'minimum cost', 'is it possible'
  • the same sub-problem is solved again and again
  • choices at each step with a clear state (index, remaining amount…)
Idea

Define the state, write the recurrence, fill the table in dependency order. If you can write the brute-force recursion, add a cache first (memoisation); convert to a table only if you need to.

Cost: O(number of states × work per state)

Python · editable
Expected output: 89 4

Practise: Climbing Stairs ↗ · Coin Change ↗ · Longest Increasing Subsequence ↗ · Longest Common Subsequence ↗ · Edit Distance ↗

Greedy Week 7

Signals
  • a locally best choice is never regretted
  • scheduling, covering, 'minimum number of…'
  • sorting by one key makes the choice obvious
Idea

Make the best-looking choice now and never revisit it. It is only correct when you can argue why (exchange argument). If a counter-example exists — coins {1, 3, 4} and amount 6 — switch to DP.

Cost: usually O(n log n) for the sort

Python · editable
Expected output: True False

Practise: Jump Game ↗ · Gas Station ↗ · Assign Cookies ↗ · Burst Balloons with Arrows ↗

Weighted shortest paths Week 5

Signals
  • edges have costs / times
  • 'cheapest route', 'minimum time to reach all nodes'
  • no negative weights (otherwise Bellman-Ford)
Idea

Dijkstra: keep a min-heap of (distance, vertex). Pop the closest, skip stale entries, relax its edges. The first time a vertex is popped its distance is final.

Cost: O((n + m) log n)

Python · editable
Expected output: {'A': 0, 'B': 3, 'C': 1, 'D': 4}

Practise: Network Delay Time ↗ · Path With Minimum Effort ↗ · Cheapest Flights Within K Stops ↗

Python toolbox for contests and interviews

ToolUse it forRemember
heapqpriority queue, top-k, DijkstraMin-heap only. Push (-x) for a max-heap; tuples compare element by element.
bisect_left / bisect_rightbinary search in a sorted list, insertion pointbisect_left(a, x) = first index with a[i] ≥ x. Insert is still O(n).
collections.dequeBFS queue, sliding-window dequepopleft() is O(1); list.pop(0) is O(n).
collections.Counterfrequencies, anagram checksCounter(a) == Counter(b); .most_common(k).
collections.defaultdictadjacency lists, groupingg = defaultdict(list); g[u].append(v) — no key checks.
functools.lru_cachememoised recursion (DP top-down)Arguments must be hashable (use tuples, not lists).
sys.setrecursionlimitdeep recursionDefault is about 1000. Prefer an explicit stack when depth can reach 10⁵.
sorted(key=…), itertoolscustom sort order, permutations, combinationssorted is stable. itertools.permutations is a generator.
Python · editable
Expected output: 1 3 3 5 {1: [2, 3], 2: [3]} 1 3

Complexity traps

TrapWhy it bitesFix
x in some_list inside a loopEach test scans the list: O(n) × n loops = O(n²)Convert to a set once
list.insert(0, x) or list.pop(0) in a loopEvery call shifts all elements: O(n) eachUse deque
s += ch building a long string in a loopMay copy the whole string each timeCollect pieces in a list and ''.join(pieces)
Slicing a[1:] in a recursive callCopies O(n) items per call, so O(n²) overallPass indices lo, hi instead
Two recursive calls where one would dof(n//2) * f(n//2) turns O(log n) into O(n)Store the result in a variable
Naive recursion with overlapping callsFibonacci-style recursion is exponentialMemoise with lru_cache or a table
Recursion depthPython stops at about 1000 frames (RecursionError)Iterate with an explicit stack, or raise the limit carefully
Counting 'amortised' as 'worst case'append is O(1) amortised: one call may cost O(n)Reason about the total over all operations

PDSA Interactive Book · Programming, Data Structures and Algorithms using Python (BSCS2002), IIT Madras BS Degree Programme.
Created by Ammar Hashmi · © 2026. An unofficial study companion — the syllabus follows the official course page and the examples are built around the PDSA Online Textbook; lectures by Prof. Madhavan Mukund (CMI). Always cross-check with the official course material.
Found a mistake or have a suggestion? Report it on GitHub ↗ · Press / to search.