Segment Trees & BIT (Fenwick Tree) — Complete Guide
Master Segment Trees and Binary Indexed Trees: range sum/min/max queries, point updates, lazy propagation, and 5-language implementations.
webcoderspeed.com
16 articles
Master Segment Trees and Binary Indexed Trees: range sum/min/max queries, point updates, lazy propagation, and 5-language implementations.
Support point updates and range sum queries. BIT (Fenwick Tree) gives O(log n) both operations with elegant implementation.
Count smaller elements to the right of each element. Process from right to left; BIT tracks seen elements. Coordinate compress values to BIT indices.
Count pairs (i,j) where i<j and nums[i] > 2*nums[j]. Modified merge sort: during merge, count pairs across left/right halves.
Book events without double-booking. Use sorted dictionary to find previous and next events; check overlap with both.
Track coverage of half-open intervals. addRange, removeRange, queryRange. Sorted dictionary of disjoint intervals with merge/split logic.
Simulate falling squares, track tallest stack height. Coordinate compress x-coordinates, use segment tree with lazy propagation for range max.
Count subarray sums within [lower, upper]. Use prefix sums and merge sort: during merge count pairs of prefix sums with difference in range.
Count all LIS of maximum length. DP: track length and count. Segment tree on values enables O(n log n) solution.
Apply range shift operations to letters. Difference array: mark +1 at start and -1 at end+1, prefix sum gives net shift at each position.
Sum of rectangle region. Precompute 2D prefix sums: prefix[i][j] = sum of all cells from (0,0) to (i-1,j-1). Inclusion-exclusion for query.
Track maximum booking overlaps at any time. Difference array: +1 at start, -1 at end; running max of prefix sum. Lazy segment tree for dynamic range.
Find max rectangle sum <= k in 2D matrix. Fix row boundaries, compress to 1D array, use prefix sums + BIT/sorted set to find best subarray sum <= k.
Find longest subarray with sum <= k. Build prefix sums, use monotonic deque for decreasing prefix sums to efficiently find left boundaries.
For each element compute product of all other elements. Two-pass: left prefix products then multiply with right suffix products.
Complete Segment Tree and BIT cheatsheet: templates for BIT, segment tree, lazy propagation, 2D BIT, and problem index.