Topic · 4 patterns
Advanced & Niche patterns
Lower priority for most product-company interviews, higher for fintech, quant and competitive programming. Segment trees and Fenwick trees answer range queries with updates in O(log n), reservoir sampling picks uniformly from a stream of unknown length, meet in the middle splits a 2ⁿ search into two 2^(n/2) halves, and matrix exponentiation computes a linear recurrence in O(k³ log n).
The patterns
Segment Tree / Fenwick (BIT)
O(log n)
A balanced tree (or BIT) over the array gives log-time queries and updates instead of O(n) rescans.
Spot it: Range queries (sum/min/max) mixed with updates, count smaller/greater seen so far, inversions, first prefix ≥ k.
Learn first: Prefix Sum
Reservoir Sampling
O(n) / O(1) space
Keep the current pick; for the i-th item, replace it with probability 1/i.
Spot it: Uniform random element from a stream or linked list of unknown length, or among matching indices, in one pass, O(1) memory.
Meet in the Middle
O(2^(n/2))
Enumerate each half (2^(n/2) each), sort one, and binary-search to combine.
Spot it: n around 35-45: 2ⁿ is too big but 2^(n/2) fits; subset/closest sum with huge values; ~20x20 grid path with XOR.
Learn first: Subsets / Permutations / Combinations, Binary Search
Matrix Exponentiation
O(k³ log n)
Express the recurrence as a matrix and raise it to the n-th power by fast exponentiation.
Spot it: Small linear recurrence at a huge index (n ~ 1e18), walks of length exactly n, or constant-size DP state with the same transition each step.
Learn first: 1D / Fibonacci-style
Which one? Match the signal
| If the problem says | Reach for |
|---|---|
| Range query (sum/min/max) WITH updates, or count smaller elements to the right | Segment Tree / Fenwick |
| Pick a random element from a stream of unknown length, one pass | Reservoir Sampling |
Easy to confuse
Count of Smaller Numbers After Self looks like Monotonic Stack, but it’s Segment Tree / Fenwick (BIT)
Counts of all smaller elements, not the nearest one: BIT over compressed values or merge-sort counting.
Random Pick with Weight looks like Reservoir Sampling, but it’s Binary Search
Weights known upfront: prefix sums + binary search, not reservoir sampling.
Minimum Number of Increments on Subarrays to Form a Target Array looks like Segment Tree / Fenwick (BIT), but it’s Difference Array & Line Sweep
Divide-and-conquer on the minimum works, but the editorial's difference-array view gives the sum of positive rises in O(n).
Remainder Problem looks like Segment Tree / Fenwick (BIT), but it’s Square Root Decomposition
'Sum over i = y mod x' has no segment-tree form. Precompute a table for x <= sqrt(N), brute force larger x.
Used together
Sweep Line (events + active set) + Segment Tree / Fenwick (BIT) + Coordinate Compression
When: area/perimeter of union of rectangles. Union area needs covered length per x-slab under range updates.
Segment Tree / Fenwick (BIT) + Coordinate Compression
When: count elements smaller/greater than x to the left/right; inversions. Counting by value needs an index structure over a huge value domain.
Offline Query Processing + Segment Tree / Fenwick (BIT)
When: distinct values / one-occurrence queries on ranges. Distinct count is not mergeable online, but becomes a prefix count when queries are sorted.
Longest Increasing Subsequence + Segment Tree / Fenwick (BIT) + Coordinate Compression
When: count increasing subsequences; LIS with weights. Counting or weighted LIS needs aggregate over all smaller values.
Segment Tree / Fenwick (BIT)
- Range Sum Query - MutableMedium
- Dynamic Range Sum QueriesMedium
Reservoir Sampling
- Linked List Random NodeMedium
- Random Pick IndexMedium
Meet in the Middle
- Apple DivisionEasy
- Meet in the MiddleMedium
Matrix Exponentiation
- Fibonacci NumberEasy
- Fibonacci NumbersMedium
Further reading
- Segment Treecp-algorithms
Definitive reference, from basics to lazy propagation.
- Fenwick Treecp-algorithms
BIT with range update/query variants.
- ITMO Segment Tree courseCodeforces EDU
Videos plus practice; the best structured seg-tree training.
- Efficient and easy segment treesAl.cash
Short iterative segment tree you can write in 2 minutes.
- Meet in the MiddleUSACO Guide
Split-and-merge search for n around 40.
- Matrix ExponentiationUSACO Guide
Linear recurrences in O(k^3 log n).
- Reservoir samplingWikipedia
Algorithm R and proof; common in fintech/infra interviews.