TRT
Sign in
hardAdvancedLeetCode#offline sweep#min-heap with lazy removal

Minimum interval to include each query

For each query point, find the length of the shortest interval containing it, by sweeping sorted queries and keeping a heap of active intervals.

The Runtime Theory Team1 min read
Taught inIntervals and sweepingPro — members onlySort intervals by start and most interval problems become a single pass: merging overlaps, inserting a new interval, or sweeping through start and end events to count how many intervals overlap at once.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inintervals = [[1, 4], [2, 4], [3, 6], [4, 4]], queries = [2, 3, 4, 5]

out[3, 3, 1, 4]

inintervals = [[2, 3], [2, 5], [1, 8], [20, 25]], queries = [2, 19, 5, 22]

out[2, -1, 4, 6]

inintervals = [[1, 2]], queries = [5]

out[-1]

Each closed interval [l, r] has size r − l + 1. For each query point, return the size of the smallest interval containing it, or -1.

Before you code

Answering queries in sorted order, instead of the given order, lets a sweep add each interval once and drop it once. Remember each query's original index to place the answer.

Hints

  1. Sort intervals by start and queries by value.
  2. For each query q: push every interval with start ≤ q into a min-heap keyed by size (with its end).
  3. Pop from the heap while the top's end is less than q: it no longer covers anything ahead.
  4. The top's size is the answer for q, or -1 if the heap is empty.

Production & complexity notes

When solving Minimum interval to include each query on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Intervals and sweeping to reinforce the underlying pattern.

What it practices

A sweep that maintains a structure of active intervals, from Intervals and sweeping.

Not started

Sign in to save your learning progress.

Sign in to save