Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns

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

  1. 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

    Learn Segment Tree / FenwickCheat sheet and practice
  2. 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.

    Learn Reservoir SamplingCheat sheet and practice
  3. 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

    Learn Meet in the MiddleCheat sheet and practice
  4. 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

    Learn Matrix ExponentiationCheat sheet and practice

Which one? Match the signal

If the problem saysReach for
Range query (sum/min/max) WITH updates, or count smaller elements to the rightSegment Tree / FenwickO(log n)
Pick a random element from a stream of unknown length, one passReservoir SamplingO(n)

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.

Where to start

then the The 128 and The 365 sheets

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

free, outside Lessgo
  • 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.

← Strings & TriesAll 49 patterns
TodayReviewPatternsProblems