Start learning free

LESSON 558 OF 673 · INTERVALS

Minimum Interval to Include Each Query in Python: Sorting and a Min-Heap

Practice O(n log n + q log q) Read the full explanation

You get a list intervals and a list queries.

Each interval is a pair [left, right]. It holds every whole number from left to right, both ends included. Its size is right - left + 1, the count of numbers it holds.

For each query, find the smallest interval that holds it. Return a list with the sizes of these intervals, in the order of queries. If no interval holds a query, its answer is -1.

 

Example 1:

Input: intervals = [[2,6],[4,5],[1,9],[8,8]], queries = [5,8,1,3]
Output: [2,1,9,5]
Explanation:
5 is in [2,6], [4,5] and [1,9]. The smallest is [4,5], size 2.
8 is in [1,9] and [8,8]. The smallest is [8,8], size 1.
1 is only in [1,9], size 9.
3 is in [2,6] and [1,9]. The smallest is [2,6], size 5.

Example 2:

Input: intervals = [[10,12],[30,31]], queries = [11,20,31,9]
Output: [3,-1,2,-1]
Explanation: 11 is in [10,12], size 3.
No interval holds 20 or 9, so their answers are -1.
31 is in [30,31], size 2.

Example 3:

Input: intervals = [[1,3],[3,5],[3,3]], queries = [3,3,4]
Output: [1,1,3]
Explanation: Both ends count, so 3 is in all three intervals.
The smallest is [3,3], size 1.
The second 3 gets the same answer.
4 is only in [3,5], size 3.

 

Constraints:

  • 1 to 100,000 intervals.
  • 1 to 100,000 queries.
  • Each left and right is a whole number from 1 to 10,000,000.
  • left is never greater than right.
  • Each query is a whole number from 1 to 10,000,000.
  • Intervals can overlap or repeat.
  • Both lists come in any order.

Note:

Your solution should run in O(n log n + q log q) time, for n intervals and q queries.

STEP 1 OF 15
    Ctrl + Enter to check

    PYTHON · INTERVALS

    Minimum Interval To Include Each Query in Python, explained

    Problem overview

    The method minInterval receives a list intervals and a list queries. Each interval is a pair [left, right] that holds every whole number from left to right, both ends included, so its size is right - left + 1. For each query, find the smallest interval that holds it. The method returns a list with those sizes, in the order of queries, and uses -1 for a query that no interval holds.

    With intervals = [[2, 6], [4, 5], [1, 9], [8, 8]] and queries = [5, 8, 1, 3] the answer is [2, 1, 9, 5]. The number 5 lies in [2, 6], [4, 5] and [1, 9], and the smallest of those is [4, 5], size 2. The number 1 lies only in [1, 9], size 9. With intervals = [[10, 12], [30, 31]] and queries = [11, 20, 31, 9] the answer is [3, -1, 2, -1], because no interval holds 20 or 9.

    The lesson asks for O(n log n + q log q) time, for n intervals and q queries. Both lists can hold 100,000 entries, in any order, and intervals may overlap or repeat.

    Approach: answer queries from small to large

    Checking every interval for every query takes O(n · q), which is 10 billion steps at the limits. The speed-up comes from the order of the work.

    Answer the queries from smallest to largest, and sort the intervals by their left end. When the query is q, the intervals that start at or before q are the only candidates, and since queries only grow, an interval that starts before one query also starts before all later ones. So each interval can be added once, when the first query reaches its start.

    The candidates are kept in a min-heap of pairs (size, right). Pairs compare by their first value, so the smallest interval is always on top. Before reading the top, drop the intervals that end before q. They can't hold q, and since later queries are larger, they can't hold any later query either. Only the top needs checking: an expired interval deeper in the heap is removed when it reaches the top.

    Everything left in the heap starts at or before q and ends at or after it, so the top is the smallest interval holding q. If the heap is empty, the answer stays -1.

    Because queries are answered out of order, we also remember each query's original position and write the result there.

    Step by step

    1. Sort intervals by left end: intervals.sort(key=lambda interval: interval[0]).
    2. Sort the query positions by value: order = sorted(range(len(queries)), key=lambda k: queries[k]). This sorts the indexes, not the values, so we keep track of where each answer belongs.
    3. Create answer = [-1] * len(queries), one -1 per query. A query that finds an interval overwrites it.
    4. Create heap = []. With the heapq module, a plain list works as a min-heap, with the smallest pair at heap[0].
    5. Create i = 0, the index of the next interval to add.
    6. Loop with k over order.
    7. Set q = queries[k], the query's value.
    8. Add the intervals that start at or before q: while i < len(intervals) and intervals[i][0] <= q, unpack start, end = intervals[i], push (end - start + 1, end) with heapq.heappush, and add 1 to i. The size goes first so the smallest interval floats to the top, and the end tells us later when the interval stops being useful.
    9. Drop the expired intervals: while heap is not empty and heap[0][1] < q, call heapq.heappop(heap).
    10. Answer the query: if heap is not empty, set answer[k] = heap[0][0].
    11. Return answer.

    On the first example, the sorted intervals are [1, 9], [2, 6], [4, 5] and [8, 8], and the sorted query positions are [2, 3, 0, 1], which are the queries 1, 3, 5 and 8. For each query, the table shows the heap after the two inner loops (pairs of size and end) and the answer:

    query 1: heap [(9, 9)]                                  answer 9
    query 3: heap [(5, 6), (9, 9)]                          answer 5
    query 5: heap [(2, 5), (5, 6), (9, 9)]                  answer 2
    query 8: heap [(1, 8), (2, 5), (5, 6), (9, 9)]          answer 1

    The heap contents are listed in sorted order here, for readability. For query 8, the pairs (2, 5) and (5, 6) are still in the heap although they ended before 8. They are not on top, so the loop leaves them alone, and they can't affect the answer: the top (1, 8) is smaller than both. If they ever reach the top, the cleanup loop drops them then. Results are written to answer[k], so the final list is [2, 1, 9, 5], in the order of the original queries.

    The solution in Python

    class Solution:
        def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
            intervals.sort(key=lambda interval: interval[0])
            order = sorted(range(len(queries)), key=lambda k: queries[k])
            answer = [-1] * len(queries)
            heap = []
            i = 0
            for k in order:
                q = queries[k]
                while i < len(intervals) and intervals[i][0] <= q:
                    start, end = intervals[i]
                    heapq.heappush(heap, (end - start + 1, end))
                    i += 1
                while heap and heap[0][1] < q:
                    heapq.heappop(heap)
                if heap:
                    answer[k] = heap[0][0]
            return answer
    

    Python details:

    • heapq is a min-heap on a plain list. heappush and heappop take O(log n), and heap[0] reads the smallest item in O(1).
    • Tuples compare element by element. Two intervals of equal size are ordered by their right end, which is harmless here.
    • sorted returns a new list, while intervals.sort(...) sorts in place and returns None. The in-place sort reorders the caller's intervals, but queries stays as it was, which matters because queries[k] is read by position.
    • while heap and ... relies on an empty list being false, and and stops before heap[0] is read on an empty heap.

    Complexity

    Time: O(n log n + q log q). Sorting the intervals costs O(n log n) and sorting the query positions O(q log q). Each interval is pushed once and popped at most once, each in O(log n), so the heap work is O(n log n). Each query adds only constant work outside those pushes and pops.

    Space: O(n + q). The heap holds up to n pairs, and order and answer hold q entries each.

    Edge cases and common mistakes

    • A query no interval holds. For [[10, 12], [30, 31]] the queries 20 and 9 stay at -1: 9 comes before every start, and for 20 the interval [10, 12] is dropped as expired.
    • Repeated queries and shared ends. For [[1, 3], [3, 5], [3, 3]] and [3, 3, 4] the answer is [1, 1, 3]. Both ends count, so 3 is in all three intervals, and the smallest is [3, 3]. The check heap[0][1] < q keeps an interval whose end equals q.
    • Writing answers in sorted order. The result must follow the original order of queries, which is why the loop writes answer[k] and not an appended value.
    • Storing only the size in the heap. Without the right end there is no way to tell when an interval has expired.
    • Forgetting the +1 in the size. The interval [8, 8] holds one number, so its size is 1, not 0.

    Testing

    Results from running the method:

    intervalsqueriesResult
    [[2, 6], [4, 5], [1, 9], [8, 8]][5, 8, 1, 3][2, 1, 9, 5]
    [[10, 12], [30, 31]][11, 20, 31, 9][3, -1, 2, -1]
    [[1, 3], [3, 5], [3, 3]][3, 3, 4][1, 1, 3]
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free