Skip to lesson

Advanced data structures in practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Synthesize Segment Trees, Fenwick Trees, Sparse Tables, and composite data structures to solve complex competitive programming and real-world systems problems.

Pattern recognition: choosing the right structure

When tackling advanced algorithmic challenges, selecting the optimal data structure is often ninety percent of the solution. If you choose an inappropriate structure, your implementation becomes unnecessarily complex, memory-heavy, or too slow to pass strict time limits.

You can systematically select the ideal data structure by evaluating three criteria: mutability, operation type, and interval overlap.

  1. Static array + Idempotent query (min, max, gcd) -> Sparse Table. Delivers O(1) query time with O(N log N) build time.
  2. Dynamic array + Point updates + Prefix/Range sums -> Fenwick Tree (Binary Indexed Tree). Minimal memory footprint (N elements), simplest code, lowest CPU cache overhead.
  3. Dynamic array + Range updates (add/assign) + Arbitrary associative operations -> Segment Tree with Lazy Propagation. Handles point and range updates in O(log N) time, but consumes 4N memory.
  4. Ordered operations + O(1) key lookups -> Composite structure (HashMap + DoublyLinkedList or TreeMap).

Coordinate compression: dealing with unbounded coordinates

A frequent hurdle in competitive programming and spatial applications is that element coordinates can range up to 10^9 or be negative, but the total number of operations or distinct coordinates N is relatively small (e.g., N <= 10^5). You cannot allocate an array or tree of size 10^9 because it requires gigabytes of memory and triggers OutOfMemoryError.

Coordinate compression solves this by mapping large sparse values into dense ranks [0..M - 1]. To compress coordinates:

  1. Collect all coordinate values that appear across updates and queries into a list.
  2. Sort the list in ascending order and eliminate duplicates.
  3. Replace each original coordinate with its index in the sorted unique array using binary search (Arrays.binarySearch in Java).

Because compression preserves relative ordering (x < y if and only if rank(x) < rank(y)), order-dependent data structures like Fenwick Trees and Segment Trees operate seamlessly on the compressed ranks. This reduces the domain size from 10^9 down to at most 2 * N, allowing standard O(N) memory allocation.

Example 1 · Coordinate Compression with Fenwick Tree

CoordinateCompressionFenwickDemo.javaJava
import java.util.*;
public class CoordinateCompressionFenwickDemo {    static class BIT {        int[] tree;        int n;        BIT(int n) { this.n = n; tree = new int[n + 1]; }        void update(int i, int delta) {            for (; i <= n; i += (i & -i)) tree[i] += delta;        }        int query(int i) {            int sum = 0;            for (; i > 0; i -= (i & -i)) sum += tree[i];            return sum;        }    }
    public static void main(String[] args) {        int[] coords = {1000000000, 5, 200000, 5, 999};        int[] sorted = Arrays.stream(coords).distinct().sorted().toArray();
        int m = sorted.length;        BIT bit = new BIT(m);
        for (int x : coords) {            int rank = Arrays.binarySearch(sorted, x) + 1; // 1-based rank            int smallerCount = bit.query(rank - 1);            System.out.println("Value " + x + " has " + smallerCount + " elements inserted before it that are smaller");            bit.update(rank, 1);        }    }}
Output
Value 1000000000 has 0 elements inserted before it that are smaller
Value 5 has 0 elements inserted before it that are smaller
Value 200000 has 1 elements inserted before it that are smaller
Value 5 has 0 elements inserted before it that are smaller
Value 999 has 2 elements inserted before it that are smaller

What this code does

  • Coordinates span from 5 up to 1,000,000,000.
  • Sorted unique ranks are: 5 (1), 999 (2), 200000 (3), 1000000000 (4).
  • BIT of size 4 processes queries in O(log M) without allocating billions of integers.

Real-world applications: rate limiters, leaderboards, and interval schedulers

Advanced data structures are not just theoretical constructs; they power foundational infrastructure in modern distributed systems.

Example 2 · Calendar Booking via TreeMap Interval Intersections

MyCalendarBookingDemo.javaJava
import java.util.*;
public class MyCalendarBookingDemo {    private TreeMap<Integer, Integer> calendar = new TreeMap<>();
    public boolean book(int start, int end) {        Integer prevStart = calendar.floorKey(start);        if (prevStart != null && calendar.get(prevStart) > start) {            return false;        }        Integer nextStart = calendar.ceilingKey(start);        if (nextStart != null && nextStart < end) {            return false;        }        calendar.put(start, end);        return true;    }
    public static void main(String[] args) {        MyCalendarBookingDemo cal = new MyCalendarBookingDemo();        System.out.println("Book [10, 20): " + cal.book(10, 20));        System.out.println("Book [15, 25): " + cal.book(15, 25));        System.out.println("Book [20, 30): " + cal.book(20, 30));    }}
Output
Book [10, 20): true
Book [15, 25): false
Book [20, 30): true

What this code does

  • [10, 20) is booked successfully.
  • [15, 25) overlaps with [10, 20) because 15 < 20, so booking is rejected.
  • [20, 30) starts exactly when the previous meeting ends, so booking succeeds.

Example 3 · Score Leaderboard via Fenwick Tree

LeaderboardRankDemo.javaJava
public class LeaderboardRankDemo {    static class ScoreTracker {        int[] tree = new int[1001]; // max score 1000
        void addScore(int score) {            for (int i = score; i < tree.length; i += (i & -i)) tree[i]++;        }
        int countWithScoreAtMost(int score) {            int sum = 0;            for (int i = score; i > 0; i -= (i & -i)) sum += tree[i];            return sum;        }
        int getRank(int score, int totalPlayers) {            int atMost = countWithScoreAtMost(score);            return totalPlayers - atMost + 1; // 1-based rank        }    }
    public static void main(String[] args) {        ScoreTracker tracker = new ScoreTracker();        int[] scores = {100, 200, 300, 200, 500};        for (int s : scores) tracker.addScore(s);
        System.out.println("Rank of score 500: " + tracker.getRank(500, 5));        System.out.println("Rank of score 200: " + tracker.getRank(200, 5));        System.out.println("Rank of score 100: " + tracker.getRank(100, 5));    }}
Output
Rank of score 500: 1
Rank of score 200: 3
Rank of score 100: 5

What this code does

  • Score 500 is the highest, ranking #1.
  • Score 200 has scores 300 and 500 strictly above it, ranking #3.
  • Score 100 is the lowest, ranking #5.

In gaming leaderboards, online multiplayer games display player rank across millions of users; a Fenwick Tree over score frequencies tracks how many players have a score greater than X in O(log S) time while updating scores in O(log S) time. In meeting schedulers like Google Calendar, a Segment Tree with lazy propagation tracks maximum concurrent bookings across time intervals, answering capacity checks and room reservations in O(log T) time. Similarly, sliding window rate limiters in API gateways protect microservices by limiting clients to N requests per minute. Maintaining timestamps in a TreeMap or ring buffer allows querying request counts in the last 60 seconds and rejecting bursts with microsecond latency.

Common pitfalls and competitive programming debugging

Three classic pitfalls break range structures: a segment tree array that is too small, a Fenwick tree that touches index 0, and an int sum that overflows. The program below shows the safe sizes and what overflow does to an int sum.

RangePitfalls.javaJava
public class RangePitfalls {    public static void main(String[] args) {        int n = 100_000;        int[] seg = new int[4 * n];      // segment tree: 4N slots, not 2N        int intSum = 0;        long longSum = 0;        for (int i = 1; i <= n; i++) {   // Fenwick indices start at 1, never 0            intSum += 1_000_000_000;            longSum += 1_000_000_000;        }        System.out.println("seg slots: " + seg.length);        System.out.println("int sum:  " + intSum);        System.out.println("long sum: " + longSum);    }}
Output
seg slots: 400000
int sum:  276447232
long sum: 100000000000000

First, never undersize the Segment Tree array: allocating 2 * N space often results in ArrayIndexOutOfBoundsException because the tree height requires up to 4 * N nodes. Always allocate int[4 * N]. Second, beware of Fenwick Tree zero indices: because 0 & (-0) = 0, operating on index 0 causes an infinite loop (i += 0); Fenwick trees must always be 1-indexed.

Finally, guard against 32-bit integer overflow: summing 10^5 elements of magnitude 10^9 reaches 10^14, which silently overflows Java's 32-bit signed int into a wrong (often negative) number. Always use primitive long for sum accumulators and tree arrays.

Finish up

Mark complete & continue

Next: Topic set: lists, stacks and queues