LeetCode 1851: Minimum Interval to Include Each Query Solution

Master LeetCode problem 1851 (Minimum Interval to Include Each Query), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1851. Minimum Interval to Include Each Query

Problem Explanation

Explanation

To solve this problem, we can use a priority queue to keep track of the intervals. We will sort the intervals based on their size in ascending order. Then, for each query, we will iterate through the sorted intervals and find the smallest interval that contains the query value.

  1. Sort the intervals based on their size.
  2. Iterate through the queries:
    • Pop intervals from the priority queue until we find an interval that contains the query value.
    • Update the answer with the size of the interval found.
    • Push back the remaining intervals to the priority queue.

The time complexity of this solution is O((n + m)logn), where n is the number of intervals and m is the number of queries. The space complexity is O(n) for the priority queue.

Solution Code

import java.util.*;

class Solution {
    public int[] minInterval(int[][] intervals, int[] queries) {
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (a[1] - a[0] - b[1] + b[0]));
        for (int[] interval : intervals) {
            pq.offer(interval);
        }
        
        int[] ans = new int[queries.length];
        Arrays.fill(ans, -1);
        
        for (int i = 0; i < queries.length; i++) {
            int query = queries[i];
            while (!pq.isEmpty()) {
                int[] interval = pq.poll();
                if (interval[0] <= query && query <= interval[1]) {
                    ans[i] = interval[1] - interval[0] + 1;
                    break;
                }
            }
            while (!pq.isEmpty()) {
                int[] interval = pq.poll();
                pq.offer(interval);
            }
        }
        
        return ans;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1851 (Minimum Interval to Include Each Query)?

This page provides optimized solutions for LeetCode problem 1851 (Minimum Interval to Include Each Query) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1851 (Minimum Interval to Include Each Query)?

The time complexity for LeetCode 1851 (Minimum Interval to Include Each Query) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1851 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1851 in Java, C++, or Python.

Back to LeetCode Solutions