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/Advanced & Niche/Segment Tree / Fenwick (BIT)

Technique

Sparse Table (static RMQ)

Precompute answers for all ranges of length 2k; idempotent queries (min, max, gcd) take O(1) by overlapping two blocks.

Learn firstBit Tricks & Bitmasking
0%
mastery
0/5 solved
Practise nextDistance Queries
IdeaPracticePitfalls

Recognise it

The signal

static array, many range min/max/gcd queries

  1. 1Brute force

    Scan each range O(n).

  2. 2The observation

    Per-query scanning: any range is the union of two overlapping power-of-two blocks.

  3. 3Why it works

    st[k][i] = op(a[i .. i+2k-1]).

Reach for it when

  • +LCA via Euler tour RMQ

Not when

  • ×updates
  • ×non-idempotent ops in O(1) (sum needs O(log n) disjoint blocks; use prefix-sum)

Practice

Next

Distance Queries

0/5 solved
  • Distance QueriesCSESMedium
  • Company Queries IICSESMedium
  • Static Range Minimum QueriesCSESMedium
  • Maximum modulo equalityCodeforces1700
  • Ant colonyCodeforces2100

Pitfalls

Misconceptions

  • !using sparse table for sums
Go deeper1 combinations · resources

Combinations

  • Euler Tour / Tree Flattening+Sparse Table (static RMQ)

    many LCA/distance queries on a static tree where O(log n) per query is too slow or you want O(1)

    Euler Tour / Tree Flattening:
    write the 2n-1 vertex visit sequence with depths
    Sparse Table (static RMQ):
    RMQ on depths gives the LCA in O(1)

    Distance QueriesCompany Queries II

Resources

  • Segment Treecp-algorithms · article
  • Fenwick Treecp-algorithms · article
  • ITMO Segment Tree courseCodeforces EDU · course
  • Efficient and easy segment treesAl.cash · blog
  • Meet in the MiddleUSACO Guide · course
  • Matrix ExponentiationUSACO Guide · course
  • Reservoir samplingWikipedia · article
TodayReviewPatternsProblems