Data Structures19 sections · 729 units
Open in Course

Range Module: TreeMap Approach

Ordered map of intervals

Use a TreeMap (sorted map) where keys are interval starts and values are interval ends.

Invariant: intervals in the map are non-overlapping and non-adjacent.

class RangeModule:
    intervals: TreeMap<int, int> // start -> end

    function addRange(left, right)
        // Find overlapping intervals
        // Merge them into [left, right]
        // Remove old intervals, insert merged

    function queryRange(left, right)
        // Find interval containing left
        // Check if its end >= right

    function removeRange(left, right)
        // Find overlapping intervals
        // Trim or split them

Each operation requires finding overlapping intervals and updating the map.