InterviewPrepKit

Home / Coding / Intervals

Minimum Interval to Include Each Query

hard Original ↗
Solving tips
  • Go OFFLINE: sort queries ascending (and intervals by left), sweep once, then map answers back to the original query order at the end.
  • As q grows, admit intervals with left <= q via a pointer into a min-heap keyed by (size, right); the heap key must be interval SIZE, the quantity you minimize, not right.
  • Discard dead intervals lazily: pop while heap top's right < q right before reading the answer; each interval is pushed and popped at most once for O((n+q) log(n+q)).
  • Pitfalls: size is right - left + 1 (closed), eviction test is strict '<' (right == q still contains q), and deduping queries handles repeats for free.

Problem

You are given a list of closed intervals [left, right] and a list of integer queries. For each query value q, find the size of the smallest interval that contains q, where an interval’s size is right - left + 1 and “contains” means left <= q <= right. If no interval contains q, the answer for that query is -1. Return the answers in the same order as the queries.

Examples

  • intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5][3,3,1,4] — e.g. query 4 fits inside [4,4], size 1; query 5 only fits [3,6], size 4.
  • intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22][2,-1,4,6] — query 19 lies in a gap, so -1; query 22 fits only [20,25], size 6.

Constraints

  • 1 <= len(intervals), len(queries) <= 10^5
  • 1 <= left <= right <= 10^7
  • 1 <= queries[i] <= 10^7

Both lists reach 10^5, so the O(n * q) scan-per-query is ~10^10 operations — the expected solution is O((n + q) log(n + q)).

Think about it first

Hint 1 Nothing forces you to answer the queries in the order given. What becomes easier if you process them in sorted order and map answers back at the end?
Hint 2 Sweeping queries in increasing order, an interval becomes relevant once its left end is ≤ the query, and becomes dead forever once its right end is < the query. What structure lets you hold the currently relevant intervals and grab the smallest one fast — even with dead ones mixed in?
Hint 3 Sort intervals by left and queries ascending. For each query: push every interval whose left ≤ q into a min-heap keyed by (size, right); then pop from the top while the top's right < q (lazily discarding dead intervals); the surviving top's size is the answer. Each interval is pushed and popped at most once across the whole sweep.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.