Range Module - Problem

A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them.

A half-open interval [left, right) denotes all the real numbers x where left <= x < right.

Implement the RangeModule class:

  • RangeModule() Initializes the object of the data structure.
  • void addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked.
  • boolean queryRange(int left, int right) Returns true if every real number in the interval [left, right) is currently being tracked, and false otherwise.
  • void removeRange(int left, int right) Stops tracking every real number currently being tracked in the half-open interval [left, right).

Input & Output

Example 1 — Basic Operations
$ Input: operations = ["RangeModule", "addRange", "removeRange", "queryRange", "queryRange"], params = [[], [10, 20], [14, 16], [10, 14], [13, 15]]
Output: [null, null, null, true, false]
💡 Note: RangeModule initializes empty. addRange(10, 20) tracks [10, 20). removeRange(14, 16) removes [14, 16), leaving [10, 14) and [16, 20). queryRange(10, 14) returns true (fully covered). queryRange(13, 15) returns false (15 not tracked).
Example 2 — Overlapping Ranges
$ Input: operations = ["RangeModule", "addRange", "addRange", "queryRange"], params = [[], [10, 15], [12, 18], [10, 18]]
Output: [null, null, null, true]
💡 Note: addRange(10, 15) tracks [10, 15). addRange(12, 18) merges with existing to track [10, 18). queryRange(10, 18) returns true (fully covered).
Example 3 — Edge Case Empty Query
$ Input: operations = ["RangeModule", "queryRange"], params = [[], [1, 5]]
Output: [null, false]
💡 Note: Empty RangeModule has no tracked ranges, so queryRange(1, 5) returns false.

Constraints

  • 1 ≤ left < right ≤ 109
  • At most 104 calls will be made to addRange, queryRange, and removeRange.

Visualization

Tap to expand
Range Module: Track Half-Open IntervalsaddRange(10, 20): Track [10, 20)[10, 20)← TrackedremoveRange(14, 16): Remove [14, 16)[10, 14)[16, 20)queryRange(10, 14): Check if [10, 14) is tracked✓ Fully covered → return truequeryRange(13, 15) → false (15 not tracked)
Understanding the Visualization
1
Add Ranges
Track half-open intervals [left, right)
2
Query Coverage
Check if range is fully tracked
3
Remove Ranges
Stop tracking specified intervals
Key Takeaway
🎯 Key Insight: Use interval merging to efficiently manage overlapping ranges and enable fast coverage queries
Asked in
Google 15 Facebook 12 Amazon 8
32.1K Views
Medium Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen