Segment Trees and Fenwick Tree — Complete Interview Guide
Master Segment Trees and Binary Indexed Trees for FAANG interviews: range sum, min, max queries, point updates, lazy propagation, 2D BIT, and full problem index with complexity reference.
14 articles
Master Segment Trees and Binary Indexed Trees for FAANG interviews: range sum, min, max queries, point updates, lazy propagation, 2D BIT, and full problem index with complexity reference.
Count smaller elements to the right of every index using a Binary Indexed Tree (Fenwick Tree) with coordinate compression. The cleanest O(n log n) solution every interviewer expects.
Count pairs (i, j) with i less than j and nums[i] greater than twice nums[j]. The classic Hard problem for modified merge sort and BIT counting — the two techniques every senior interviewer expects.
Design a calendar that rejects double bookings. The classic interval-overlap interview problem solved with sorted maps in O(log n) per booking — the foundation for every range scheduling system.
Track range coverage with addRange, removeRange, and queryRange. Maintain disjoint intervals in a sorted map for amortized O(log n) — the canonical interview problem for interval merging logic.
Track the tallest stack height as squares fall onto a number line. The textbook problem for segment trees with lazy propagation, range max queries, and range-assign updates.
Count subarray sums in [lower, upper] using merge sort or Fenwick tree on prefix sums. The flagship Hard problem connecting prefix sums, divide-and-conquer counting, and BIT range queries.
Count all longest increasing subsequences with DP in O(n^2) or with a segment tree on values for O(n log n). The classic crossover problem between DP and range-query data structures.
Apply many range shift operations to a string in O(n + q) using a difference array. The textbook example of when a diff array beats a segment tree, and the canonical interview signal for offline range updates.
Master LeetCode 304 Range Sum Query 2D Immutable with 2D prefix sums, inclusion-exclusion, and the natural extension to 2D Fenwick tree (BIT) for the mutable variant.
Solve LeetCode 732 My Calendar III using a sweep-line difference array in O(n) per booking, then upgrade to a dynamic lazy segment tree with coordinate compression for O(log n) range updates and max queries.
Crack LeetCode 363 Max Sum of Rectangle No Larger Than K by fixing two row boundaries to collapse 2D into 1D, then using prefix sums plus a sorted set (or BIT/segment tree) to find the best subarray sum bounded above by K.
Find the longest contiguous subarray whose sum is at most K in linear time using prefix sums plus a decreasing monotonic stack, then learn the segment tree and BIT alternatives for streaming variants.
Solve LeetCode 238 Product of Array Except Self in O(n) time and O(1) extra space using two passes of prefix and suffix products, with the segment tree and Fenwick tree extensions for the mutable variant.