Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Range Query Patterns
DSA

Range Query Patterns

Learn techniques for efficiently answering repeated queries over ranges of an array.

Range queries are about picking the cheapest structure that satisfies your update pattern.

Think range query structures when you see:

  • Repeated sum/min/max over subranges
  • “Count inversions / smaller elements to the left”
  • Static array with many O(1) min queries
  • Point updates + prefix aggregates

Quick Recognition Cheat Sheet

If you see…Think…Why
Prefix sums, no updatesPrefix Sum arrayO(n) build, O(1) query
Point update + prefix sumFenwick treeTiny code, O(log n) both
Immutable + O(1) min/maxSparse tableO(n log n) build, O(1) query
Range update + range aggregateSegment tree lazyFull flexibility
Kth order statistic updatesFenwick over valuesBinary search on the BIT

Pattern Table

StructureBuildQueryUpdateCode size
Prefix sumO(n)O(1)O(n) ❌tiny
Fenwick (BIT)O(n log n)O(log n)O(log n)~15 lines
Sparse tableO(n log n)O(1)none ❌~20 lines
Segment treeO(n)O(log n)O(log n)~50 lines

Mental Trigger

No updates → prefix/sparse. Updates → Fenwick. Range updates → segment tree lazy.

Decision Guide

Static data?
    ├─ sum only        → Prefix Sum
    └─ min/max/gcd     → Sparse Table

Dynamic data?
    ├─ point add + prefix sum   → Fenwick Tree
    ├─ need min/max too         → Segment Tree
    └─ range updates            → Segment Tree + Lazy

My Private Notes

Notes are auto-saved locally to this device.