AlgoMaster Logo

Minimum Interval to Include Each Query

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

In the brute force approach, we will iterate over each query and for each query, traverse through all the intervals to check which interval can contain the query, then select the smallest interval among those that can accommodate the query.

Steps:

  1. For each query, iterate through each interval.
  2. For each query, find all intervals [start, end] where start <= query <= end.
  3. Out of these suitable intervals, select the interval of minimum length (end - start + 1).
  4. Store the result for each query.

Code:

2. Sorting and Two Pointers with Priority Queue

Intuition:

The brute force solution is not efficient enough for larger inputs. To optimize, we can use a combination of sorting and priority queue:

  • Sort the intervals and queries.
  • Use a priority queue to keep track of interval sizes as we move through the intervals and handle queries.

Steps:

  1. Sort intervals by their start points.
  2. Sort queries along with their indices so that we can retrieve the result in original order.
  3. Use a min-heap (priority queue) to store intervals based on their end points while processing queries.
  4. For each query, filter intervals that can cover the query and add them to the priority queue.
  5. Remove the intervals from the priority queue which can no longer cover future queries.
  6. The smallest element in the priority queue will be the minimum interval for the current query.

Code:

Complexity Analysis:

  • Time Complexity: (O(m + n) log m), where n is the number of queries and m is the number of intervals. This includes sorting intervals, queries and operations related to priority queue.
  • Space Complexity: O(m), for storing intervals that are currently being considered in the priority queue.