Skip to main content
← CONCEPTS / ALGORITHMS-DATA-STRUCTURES
An end-to-end domain learning journey

Binary Indexed Tree: Difference Arrays,
Range Updates & Binary Lifting.

Beyond basic point-update prefix sums, Binary Indexed Trees (Fenwick Trees) support O(log N) range-add + range-sum via dual difference arrays and O(log N) k-th order-statistic search via binary lifting in a flat N+1 array.
Start the journey7 sections· Last modified Nov 26, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

Pairing `BIT1(D[i])` and `BIT2((i-1)*D[i])` unlocks full O(log N) range updates and sums without Segment Tree lazy propagation.

TL;DR30-second simplified summary
▾

Fenwick Trees initialize in O(N) via parent propagation tree[i + (i & -i)] += tree[i]. Storing a difference array supports O(log N) range adds with O(log N) point reads.

Adding a second BIT for (i-1)*D[i] enables both O(log N) range adds and range sums in half the memory of a 4N Segment Tree.

Full walkthrough · 7 stages
01
foundation

Stage 1: Lowest-Set-Bit Responsibility (idx & -idx).

Why this matters: Understand how two's-complement bit isolation maps each 1-indexed slot to its power-of-two subrange.

In two's complement, -idx flips all bits and adds 1, so idx & -idx isolates the lowest set bit (LSB). Slot BIT[idx] stores the sum of the lsb = idx & -idx elements ending at idx: [idx - lsb + 1 .. idx]. Because indices must be 1-based (0 has 0 & 0 == 0 which would loop forever), the array has length N + 1.

FOUNDATION · TWO'S COMPLEMENT LSB

Mapping BIT[1..8] to Power-of-Two Subranges via idx & -idx

1-Indexed Slot (idx>= 1)Index Guardlsb = idx & -idxRange LengthSubrange [idx-lsb+1.. idx]Bucket SpanFlat (N+1) Int64ArrayCompact LayoutAssign bucket span

1.Zero Pointer Chasing: A flat (N+1) array fits in ~8 MB for N=1M (vs 32+ MB for a 4N Segment Tree), boosting L3 cache hits.

2.1-Based Invariant: Always guard idx >= 1 before entering while loops so idx=0 never stalls.

Isolating idx & -idx assigns each 1-based slot a power-of-two subrange inside a compact (N+1) contiguous array.

02
foundation

Stage 2: O(log N) Point Update & Prefix Query Loops.

Why this matters: Trace upward parent jumps (idx += idx & -idx) and downward prefix jumps (idx -= idx & -idx).

To add delta at idx, we walk upward to every covering ancestor via idx += idx & -idx until idx > N. To compute prefix_sum(idx), we accumulate BIT[idx] and strip the lowest set bit via idx -= idx & -idx until idx == 0. Both loops execute at most floor(log2(N)) + 1 iterations (<= 20 ops for N=1M).

FOUNDATION · CORE OPERATIONS

<= 20 Bit Operations per Update or Prefix Sum at N = 1,000,000

Point Update: idx+= lsbUpward PathPrefix Query: idx -=lsbDownward PathRange Sum(L, R)Invertible OpMax 20 Iterations(N=1M)O(log N) BoundSubtract L-1 prefix

1.Invertibility Requirement: Range Sum(L, R) = prefix(R) - prefix(L-1) requires an invertible operator (+/XOR); use Segment Trees for min/max.

2.O(N) Linear Build: Building a BIT from an initial array takes O(N) by propagating tree[i] directly to tree[i + (i & -i)].

Upward += lsb updates and downward -= lsb prefix queries run iteratively in <= 20 bit ops for N=1,000,000.

03
intermediate

Stage 3: O(N) Linear-Time Construction.

Why this matters: Initialize a Fenwick Tree from an existing N-element array in O(N) instead of O(N log N).

Calling add(i, arr[i]) N times takes O(N log N). Instead, copy arr into tree[1..N] and in a single linear pass i = 1..N, add tree[i] directly to its immediate parent j = i + (i & -i) if j <= N. Each element is touched once, cutting initialization time by ~10x at N=1M.

INTERMEDIATE · O(N) INITIALIZATION

Single-Pass Parent Propagation in O(N) Time

Copy arr[0..N-1] ->tree[1..N]Base Loadparent = i + (i &-i)Link Steptree[parent] +=tree[i]PropagateReady in O(N) TimeInitializedIf parent <= N

1.Cache-Sequential: Linear sweep over tree[1..N] is hardware-prefetcher friendly.

2.Exact Equivalence: Every slot receives the exact sum of its direct and transitive children in topological order.

Propagating each slot to its immediate parent i + (i & -i) builds the Fenwick Tree in O(N) time.

04
intermediate

Stage 4: Range Update + Point Query via Difference Array.

Why this matters: Support O(log N) range additions [L, R] += delta with O(log N) point reads using a single BIT.

If a workload needs range additions [L, R] += val and single-point queries get(i), store the difference array D[i] = A[i] - A[i-1] inside a single Fenwick Tree. Range add [L, R] += val becomes two point updates: add(L, +val) and add(R + 1, -val), while get(i) is simply prefix_sum(i).

INTERMEDIATE · DIFFERENCE ARRAY BIT

Two-Point Range Add & Prefix Point Read in 1 Fenwick Tree

Difference ArrayD[i]Invariantbit.add(L, +val)Left Edgebit.add(R + 1,-val)Right Edgeget(i) =bit.prefix_sum(i)Point QueryUpdate R+1

1.Zero Lazy Propagation: Unlike Segment Trees, difference-array BIT needs zero lazy-tag pushdown logic.

2.2x Updates Per Range: Each range update touches at most 40 array elements for N=1M.

Storing a difference array in one Fenwick Tree turns range additions into two point updates and point reads into prefix sums.

05
intermediate

Stage 5: Dual-BIT for Both Range Updates & Range Sums.

Why this matters: Achieve O(log N) range-add AND O(log N) range-sum using two coupled Fenwick Trees.

From sum(1..r) A[i] = sum_{i=1..r} sum_{j=1..i} D[j], rearranging the double sum yields (r + 1) * sum(D[1..r]) - sum(i * D[i] for i in 1..r) (or r * sum(D[1..r]) - sum((i-1) * D[i])). Maintaining BIT1 for D[i] and BIT2 for (i-1)*D[i] gives full O(log N) range-add and range-sum in 2N+2 integers.

INTERMEDIATE · DUAL-BIT RANGE SUM

Coupled BIT1(D[i]) + BIT2((i-1)*D[i]) for Range Add & Range Sum

BIT1: D[i]First BITBIT2: (i-1)*D[i]Second BITr * Query1(r) -Query2(r)Algebraic Identity2N+2 Int64FootprintMemory WinSubtract offset sum

1.2x Smaller Than SegTree: Dual BIT uses 2N ints vs 4N (or 8N with lazy tags) for a Segment Tree.

2.64-Bit Overflow Guard: Because BIT2 stores i * D[i], always use 64-bit integers (int64) when N * val > 2^31.

Coupling BIT1(D[i]) and BIT2((i-1)*D[i]) supports both O(log N) range updates and O(log N) range sums in 2N+2 ints.

06
advanced

Stage 6: O(log N) Binary Lifting for k-th Order Statistics.

Why this matters: Find the k-th smallest element or P99 quantile bucket in a single O(log N) pass without binary search.

A naive binary_search + prefix_sum takes O(log^2 N) (~400 ops at N=1M). Binary Lifting exploits the power-of-two structure of BIT: iterating bit = 2^floor(log2(N)) down to 1, if pos + bit <= N and acc + BIT[pos + bit] < k, we advance pos += bit and acc += BIT[pos] in one O(log N) pass (~20 ops).

ADVANCED · BINARY LIFTING

Single-Pass O(log N) Quantile & Order-Statistic Search

Target Rank k (orP99)Query TargetStep = 2^19 .. 2^0Bit Walkeracc +tree[pos+step] < kGreedy GuardReturn pos + 1Order StatisticTest power-of-two block

1.20x Faster Than Binary Search: Binary lifting drops P99 quantile lookup from O(log^2 N) (~400 ops) to O(log N) (<= 20 ops).

2.Non-Negative Frequencies: Binary lifting requires all underlying frequencies >= 0 so prefix sums are monotonic.

Binary lifting walks powers of two top-down over BIT[] to locate the k-th order statistic or quantile in a single O(log N) pass.

07
advanced

Stage 7: Coordinate Compression & 2D Fenwick Extensions.

Why this matters: Handle sparse 64-bit prices/timestamps and 2D spatial grids cleanly within bounded memory.

When keys span 64-bit integers (like nanosecond latencies or arbitrary stock prices), Coordinate Compression sorts unique keys offline and maps each key to 1..U via bisect_left before indexing into the BIT. For 2D grids (R x C), nesting a BIT of BITs computes rectangle sums in O(log R * log C).

ADVANCED · SPARSE KEYS & 2D

Mapping Sparse 64-Bit Keys to Dense 1..U BIT Indices

Sparse 64-BitPrices/TimesRaw DomainDeduplicate & SortOffline Mapbisect_left(key) +1MapperDense BIT[1..U]Compact IndexBinary search index

1.Fixed-Bucket Alternative: For streaming telemetry where keys aren't known upfront, use log-linear HDR histogram buckets.

2.2D BIT Trade-off: A 2D BIT takes O(R * C) space and O(log R * log C) time—great for dense grids up to ~4096x4096.

Coordinate compression maps sparse 64-bit domains into dense 1..U indices for compact O(log U) Fenwick Tree operations.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why must a Fenwick Tree always use 1-based indexing (`1..N`) rather than 0-based indexing?

Recommended Learning Flow