Command Palette

Search for a command to run...

Module 36

Advanced Data Structures

Range queries on changing data: Fenwick trees, segment trees, lazy propagation, sparse tables, ordered maps and coordinate compression.

Advanced 3 lessons 6 problems ~40 min of lessons

Prefix sums answer range sums in O(1), but a single update forces an O(n) rebuild. When queries and updates are interleaved, you need a structure that keeps partial answers for blocks of the array, so both operations touch only O(log n) blocks.

This module builds the Fenwick (binary indexed) tree for sums and counts, the segment tree for any associative operation (min, max, sum, gcd), explains lazy propagation for range updates and sparse tables for static minimums, and shows how ordered maps and coordinate compression handle large or sparse values. The problems use them for counting inversions, smaller elements, range sums and constrained subsequences.

Best after: Prefix Sum, Binary Trees

Where this shows up in real systems

Part 1

Learn the ideas

Part 2

Solve the problems

Work through them in order. Each one shows the pattern it teaches.

  1. A Fenwick tree behind a class: point updates and range sums in O(log n).

  2. Scan from the right, counting with a Fenwick tree over (compressed) values.

  3. Merge sort counting with a different comparison (nums[i] > 2 × nums[j]) before merging.

  4. Prefix sums turn "subarray sum in [lower, upper]" into counting pairs of prefixes, done with merge sort.

  5. An ordered map answers "does this overlap the nearest bookings?" in O(log n).

  6. A segment tree over values answers "best LIS ending at a value in [v − k, v − 1]" in O(log V).