CodeArchon

hardIntervalsGoogle

Shortest Covering Interval

For each query timestamp, pick the SHORTEST interval that covers it; emit -1 if none covers.

Given intervals (as [start, end] inclusive) and queries, for each query q return the size of the smallest interval that contains q, or -1.

Choose approach

1/5
Narrationstep 1 of 5

Query 2: smallest covering interval size = 3.

1import heapq
2def minInterval(intervals, queries):
3 intervals.sort()
4 sortedQ = sorted((q, i) for i, q in enumerate(queries))
5 ans = [-1] * len(queries)
6 heap = []
7 i = 0
8 for q, idx in sortedQ:
9 while i < len(intervals) and intervals[i][0] <= q:
10 size = intervals[i][1] - intervals[i][0] + 1
11 heapq.heappush(heap, (size, intervals[i][1]))
12 i += 1
13 while heap and heap[0][1] < q: heapq.heappop(heap)
14 ans[idx] = heap[0][0] if heap else -1
15 return ans
Variables
q=2
size=3

How to think about it

  1. Offline sorting lets us process queries in monotonic order.
  2. Heap tracks live candidates by size.

Edge cases to catch in interview

  • No interval covers q -> -1.
  • Multiple intervals equal size -> any one chosen.

Examples

Example 1[2,-1,4,6]
{"intervals":[[2,3],[2,5],[1,8],[20,25]],"queries":[2,19,5,22]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed