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)

O(log n)

A balanced tree (or BIT) over the array gives log-time queries and updates instead of O(n) rescans.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
Learn firstPrefix SumUnlocksHeavy-Light DecompositionDSU with Rollback / Offline Dynamic ConnectivityParallel Binary SearchCDQ Divide and Conquer
0%
mastery
0/54 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Range queries (sum/min/max) mixed with updates, count smaller/greater seen so far, inversions, first prefix ≥ k.

  1. 1Brute force

    Recompute each query O(n).

  2. 2The observation

    Per-query linear scans: precomputed range summaries combine in O(log n).

  3. 3Why it works

    Each node stores the combined value of its range; an update fixes only its O(log n) ancestors.

Reach for it when

  • +count elements smaller/greater than x seen so far
  • +inversions
  • +find first position with prefix >= k (descend)

Not when

  • ×No updates at alluse Prefix sums (or sparse table for min/max)
  • ×The merge isn't associativeuse Not a segment tree
  • ×Range updates, not just point updatesuse Lazy segment tree

Practice

Next · Foundation

Range Sum Query - Mutable

Fenwick or iterative segment tree.

0/54 solved
  • Range Sum Query - MutableFoundationFoundationGoogle, CitadelMedium
  • Dynamic Range Sum QueriesApply it · Same at 2e5.Apply itCSESMedium
  • Dynamic Range Minimum QueriesOne change · Range minimum with updates.One changeCSESMedium
  • Range Update QueriesOne change · Range add, point query.One changeCSESMedium
  • Count of Smaller Numbers After SelfTwists · Query over values, not positions.TwistsGoogle, CitadelHard
  • Hotel QueriesBranches · Find the first position with value >= x.BranchesCSESMedium
  • Reverse PairsCombine · Condition a[i] > 2*a[j].CombineGoogle, CitadelHard
  • Range Updates and SumsAdvanced · Range assign and range add with range sum.AdvancedCSESMedium
  • Distinct Values QueriesMastery checkMastery checkCSESMedium
  • The Skyline ProblemGoogle, AmazonHard
  • Queue Reconstruction by HeightGoogle, UberMedium
  • Josephus Problem IICSESHard

Pitfalls

Classic bugs

  • !Fenwick range queries need an invertible op (sum, xor) — use a segment tree for range min/max.
  • !After a point update, recompute every ancestor on the path to the root, not just the leaf.

Looks like it, isn't

  • Minimum Number of Increments on Subarrays to Form a Target Array needs Difference Array & Line Sweep
    Why
    Divide-and-conquer on the minimum works, but the editorial's difference-array view gives the sum of positive rises in O(n). source ↗
  • Remainder Problem needs Square Root Decomposition
    Why
    'Sum over i = y mod x' has no segment-tree form. Precompute a table for x <= sqrt(N), brute force larger x. source ↗
Go deepervariants and techniques · 16 combinations · resources

Variants and techniques

  • Coordinate CompressionReplace large or sparse coordinates by their ranks among all values that matter, so arrays, BITs, and segment trees can index them.
  • Sparse Table (static RMQ)Precompute answers for all ranges of length 2^k; idempotent queries (min, max, gcd) take O(1) by overlapping two blocks.
  • Lazy Propagation Segment TreeStore pending range updates at nodes and push them down only when a child is visited, so range assign/add + range query is O(log n).
  • Persistent Segment TreeOn each update copy only the O(log n) changed nodes, keeping every past version queryable.
  • Square Root DecompositionSplit the array into ~sqrt(n) blocks with per-block summaries so updates and queries cost O(sqrt n).
  • Offline Query ProcessingRead all queries first and answer them in an order (by threshold, right endpoint, or reversed time) that turns a hard online problem into incremental updates.

Combinations

  • Difference Array & Line Sweep+Coordinate Compression

    concurrency/overlap counts with huge time values

    Difference Array & Line Sweep:
    range add as two point events
    Coordinate Compression:
    maps 1e9 coordinates to dense indices

    Number of Flowers in Full BloomMy Calendar III

  • Sweep Line (events + active set)+Segment Tree / Fenwick (BIT)+Coordinate Compression

    area/perimeter of union of rectangles

    Sweep Line (events + active set):
    moves over x events
    Segment Tree / Fenwick (BIT):
    maintains covered length on y with range add
    Coordinate Compression:
    maps y endpoints to segment tree leaves

    Area of RectanglesRectangle Area II

  • Segment Tree / Fenwick (BIT)+Coordinate Compression

    count elements smaller/greater than x to the left/right; inversions

    Segment Tree / Fenwick (BIT):
    counts values in ranges (BIT)
    Coordinate Compression:
    maps values to ranks

    Count of Smaller Numbers After SelfReverse PairsSalary Queries

  • Offline Query Processing+Segment Tree / Fenwick (BIT)

    distinct values / one-occurrence queries on ranges

    Offline Query Processing:
    sorts queries by right endpoint
    Segment Tree / Fenwick (BIT):
    BIT keeps only the latest occurrence of each value

    Distinct Values QueriesOne Occurrence

  • Offline Query Processing+Union-Find (Disjoint Set)

    queries 'connected using edges with weight < limit'; reverse deletions

    Offline Query Processing:
    sorts edges and queries by threshold
    Union-Find (Disjoint Set):
    adds edges incrementally

    Checking Existence of Edge Length Limited PathsNetwork Breakdown

  • Binary (XOR) Trie+Offline Query Processing

    max XOR with an element <= m_i

    Binary (XOR) Trie:
    max XOR with inserted numbers
    Offline Query Processing:
    sorts queries by limit so only allowed numbers are inserted

    Maximum XOR With an Element From Array

  • Longest Increasing Subsequence+Segment Tree / Fenwick (BIT)+Coordinate Compression

    count increasing subsequences; LIS with weights

    Longest Increasing Subsequence:
    dp over chains ending at each value
    Segment Tree / Fenwick (BIT):
    prefix max/sum over smaller values
    Coordinate Compression:
    value ranks

    Increasing Subsequence II

  • Euler Tour / Tree Flattening+Segment Tree / Fenwick (BIT)

    subtree sum with value updates; root-to-node path sums

    Euler Tour / Tree Flattening:
    flattens subtrees into ranges
    Segment Tree / Fenwick (BIT):
    range sums with point updates

    Subtree QueriesPath Queries

  • Heavy-Light Decomposition+Segment Tree / Fenwick (BIT)

    max/sum on path u-v with point updates

    Heavy-Light Decomposition:
    maps each path to O(log n) contiguous ranges
    Segment Tree / Fenwick (BIT):
    range max/sum per chain

    Path Queries II

  • 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

  • Sweep Line (events + active set)+Segment Tree / Fenwick (BIT)

    count intersections of axis-parallel segments, or points dominated by a query in 2D, offline

    Sweep Line (events + active set):
    process vertical segments and horizontal endpoints in x order
    Segment Tree / Fenwick (BIT):
    a BIT over y counts the active horizontals in [y1, y2]

    Intersection PointsMaximum Sum Queries

  • DSU with Rollback / Offline Dynamic Connectivity+Segment Tree / Fenwick (BIT)+Offline Query Processing

    add edge / remove edge / count components (or check bipartiteness) with all operations given upfront

    DSU with Rollback / Offline Dynamic Connectivity:
    unite on entry, roll back on exit
    Segment Tree / Fenwick (BIT):
    a segment tree over time storing each edge in the O(log q) nodes covering its lifetime
    Offline Query Processing:
    every add/remove/query must be known before processing

    Dynamic ConnectivityExtending Set of PointsBipartite Checking

  • Kruskal Reconstruction Tree+Euler Tour / Tree Flattening+Segment Tree / Fenwick (BIT)

    edges deleted over time, plus queries for the max value in v's current component

    Kruskal Reconstruction Tree:
    the threshold-reachable set is a subtree
    Euler Tour / Tree Flattening:
    that subtree is a contiguous leaf range
    Segment Tree / Fenwick (BIT):
    range max with point delete over the leaf order

    Graph and Queries

  • Manhattan <-> Chebyshev Rotation+Segment Tree / Fenwick (BIT)

    max Manhattan distance among points in an index range, with updates, k <= 5

    Manhattan <-> Chebyshev Rotation:
    2^(k-1) sign patterns turn L1 distance into max - min
    Segment Tree / Fenwick (BIT):
    range max and min per sign pattern, with point updates

    Multidimensional Queries

  • CDQ Divide and Conquer+Segment Tree / Fenwick (BIT)

    2D point updates/queries (or swaps in permutations) all offline, n ~ 2e5

    CDQ Divide and Conquer:
    split operations by time; left updates feed right queries
    Segment Tree / Fenwick (BIT):
    a BIT over one coordinate during the merge sweep

    Intersection of PermutationsLittle Artem and Time Machine

  • Binary (XOR) Trie+Tree DFS (Paths & Recursion)+Offline Query Processing

    max XOR of a value with any ancestor of a node, many queries

    Binary (XOR) Trie:
    the max XOR against values on the root path (counts per trie node allow removal)
    Tree DFS (Paths & Recursion):
    on entry insert the node's value, on exit remove it
    Offline Query Processing:
    attach the queries to their nodes

    Maximum Genetic Difference Query

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
Math / Number TheoryReservoir Sampling
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial