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

Square Root Decomposition

Split the array into ~sqrt(n) blocks with per-block summaries so updates and queries cost O(sqrt n).

Learn firstPrefix Sum
0%
mastery
0/2 solved
Practise nextRemainder Problem
IdeaPracticePitfalls

Recognise it

The signal

operations hard to merge in a segment tree

  1. 1Brute force

    O(n) per query.

  2. 2The observation

    Full scans: whole blocks are answered from summaries; only two partial blocks are scanned.

  3. 3Why it works

    Each block's summary matches its elements after every update.

Reach for it when

  • +n, q ~ 1e5 with a 2-5 second limit
  • +rebuild periodically (query batching)

Not when

  • ×a log-time structure fits (prefer seg-tree)

Practice

Next

Remainder Problem

0/2 solved
  • Remainder ProblemCodeforces2100
  • Array QueriesCodeforces2000

Pitfalls

Misconceptions

  • !block size choice ignored (balance update vs query cost)
Go deepervariants and techniques · 2 combinations · resources

Variants and techniques

  • Mo's Algorithm (offline range queries)Sort range queries by (block of l, r) and move two pointers between consecutive queries, maintaining a window summary with O(1) add/remove.

Combinations

  • Mo's Algorithm (offline range queries)+Prefix Sum+Hash Map / Hash Set Lookup

    count subarrays in [l, r] with a pair property, many offline queries

    Mo's Algorithm (offline range queries):
    moves the query window
    Prefix Sum:
    subarray XOR as prefix XOR pair
    Hash Map / Hash Set Lookup:
    frequency counts of prefix values in the window

    XOR and Favorite Number

  • Mo's Algorithm (offline range queries)+Euler Tour / Tree Flattening+Hash Map / Hash Set Lookup

    many offline path queries counting pairs/distinct values on tree paths

    Mo's Algorithm (offline range queries):
    path = range with odd-toggle membership plus the LCA
    Euler Tour / Tree Flattening:
    a 2n entry/exit sequence
    Hash Map / Hash Set Lookup:
    frequency counts by value or gender pair

    Dating

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