Minimum Interval Selection to Cover Target Intervals solution and explanation
3 more videos on this problem
Leetcode 4086 | Minimum Interval Selection to Cover Target Intervals | Leetcode weekly contest 524CodeWithMeGuys · 25:07 · 324 views
Minimum Interval Selection to Cover Target Intervals | Sort, Merge and Greedily Pick | Leetcode 4086Manjeet Dhayal · 12:14 · 135 views
LeetCode 4086. Minimum Interval Selection to Cover Target Intervals | Weekly Contest 524 Q4WiniQuest · 32:13 · 111 views
LeetCode 4086 Minimum Interval Selection to Cover Target Intervals — furthest-reach greedy, provedPrateek Goel · 14:24 · 51 views
The problem
You are given two 2D integer arrays, availableIntervals and targetIntervals, each representing a list of closed intervals.
Select a subset of intervals from availableIntervals so that every real point contained in any interval in targetIntervals belongs to at least one selected interval.
Points outside the target intervals do not need to be covered. Selected intervals may overlap or extend beyond the target intervals.
Return the minimum number of intervals you need to select. If it is impossible to cover all the target intervals, return -1.
Example 1:
Input: availableIntervals = [[1,4],[1,7],[3,9],[5,10],[10,15]], targetIntervals = [[1,3],[2,5],[7,8],[10,13],[11,15],[12,13]]
Output: 3
Explanation:
The target intervals cover the ranges [1, 5], [7, 8], and [10, 15]. By selecting [1, 4], [3, 9], and [10, 15] from availableIntervals, all target intervals can be fully covered with three intervals.
Example 2:
Input: availableIntervals = [[4,6],[1,4],[2,5]], targetIntervals = [[3,4],[2,5],[6,7]]
Output: -1
Explanation:
It is impossible to select intervals from availableIntervals to cover all the intervals in targetIntervals.
Example 3:
Input: availableIntervals = [[1,2],[3,4]], targetIntervals = [[1,4]]
Output: -1
Explanation:
Selecting both available intervals leaves every real point strictly between 2 and 3 uncovered. For example, 2.5 belongs to the target interval but to neither available interval.
Constraints:
1 <= availableIntervals.length, targetIntervals.length <= 5 * 104availableIntervals[i].length == targetIntervals[j].length == 21 <= availableIntervals[i][0] <= availableIntervals[i][1] <= 1051 <= targetIntervals[j][0] <= targetIntervals[j][1] <= 105
Approach overview
Problem Overview: You get a list of candidate intervals and a list of target intervals. Select the fewest candidate intervals so that every target interval is fully contained inside at least one selected interval.
Approach 1: Brute Force Subset Search (O(2^n * m) Time, O(n) Space)
Generate every subset of the candidate intervals and check whether each subset covers all targets. For each subset, test every target against the selected intervals. Track the smallest valid subset. This is correct but exponential. It only works as a baseline to confirm your understanding of what "covered" means.
Approach 2: Greedy with Sorting and Sweep (O(n log n + m log m) Time, O(n + m) Space)
Sort the targets by right endpoint and the candidates by left endpoint. Sweep through the targets in order. For each uncovered target, look at every candidate whose left endpoint is at or before the target's left endpoint, and pick the one with the largest right endpoint that still reaches the target. Each pick advances coverage as far as possible, so the greedy choice never hurts. Use a pointer into the sorted candidates so you never rescan. This is the standard greedy interval covering pattern and it is the approach you should aim for.
Approach 3: Sorted Candidates with Heap-Based Selection (O(n log n + m log n) Time, O(n) Space)
Sort candidates by left endpoint and push eligible ones into a max-heap keyed by right endpoint as you advance through targets. When a target needs coverage, pop the heap top to get the candidate that reaches farthest. Discard candidates that cannot reach the current target. This gives the same answer as Approach 2 and makes the "best candidate so far" logic explicit. It is useful when the eligibility test is more complex than a simple endpoint comparison.
Recommended for interviews: Start by describing the brute force so the interviewer sees you understand the coverage condition. Then move to the greedy sweep in Approach 2. The brute force shows understanding, but the greedy proof and the sorting-based sweep show skill. Be ready to explain why picking the reachable candidate with the farthest right endpoint is always safe.
Solution
Thinking
Both arrays can contain
5 times 10^4intervals, so enumerating subsets cannot check that every real point of every target is covered. Coordinates only go up to10^5, and a difference array could mark the union of the targets, but points in the gaps between those pieces have no coverage requirement.Targets overlap, and the gaps separate them. Once a left-to-right sweep records how far the selected intervals already reach, the next choice depends only on the next real point that must still lie in some selected interval.
After both arrays are sorted by left endpoint, if coverage already reaches
cur, the next required point of target[l, r]ismax(l, cur). Extend fromcurwhen that point lies inside the target. Whenlis farther right, the open interval between them belongs to no target, so those points do not need to be covered. Every available interval that contains the point has a left endpoint no larger than the point, and the one with the farthest right endpoint can replace any other choice without increasing how many intervals are still needed.The required point only moves right, so one pointer can scan the available intervals by left endpoint. An interval that does not extend past the covered position cannot fill the real points that remain inside the target.
Sort availableIntervals and targetIntervals by left endpoint. cur is the rightmost point already covered and starts at 0. Pointer i scans the available intervals from left to right.
Process each target [l, r] in that order. The target is already covered when cur \ge r. Otherwise set uncover = max(l, cur), and let nxt be the maximum right endpoint among available intervals whose left endpoint is at most uncover. If nxt < uncover, no available interval contains that point. If nxt = cur, coverage cannot move any farther right. Both cases return -1. Otherwise select the interval with that farthest right endpoint, set cur = nxt, and add 1 to the answer, until cur \ge r.
Closed intervals form one continuous cover only when they meet at an endpoint. If one selected interval ends where the next begins, no real point between them is missing. If the next left endpoint is at least 1 larger than the previous right endpoint and that gap lies inside a target, the real points in the gap are uncovered and the search returns -1.
Each interval is scanned once. The time complexity is O(n log n + m log m) and the space complexity is O(log n + log m), where n and m are the numbers of available intervals and target intervals.
class Solution:
def minSelection(
self, availableIntervals: list[list[int]], targetIntervals: list[list[int]]
) -> int:
availableIntervals.sort(key=lambda x: x[0])
targetIntervals.sort(key=lambda x: x[0])
ans = cur = 0
i = 0
for l, r in targetIntervals:
while cur < r:
uncover = max(l, cur)
nxt = cur
while (
i < len(availableIntervals) and availableIntervals[i][0] <= uncover
):
nxt = max(nxt, availableIntervals[i][1])
i += 1
if nxt < uncover or nxt == cur:
return -1
cur = nxt
ans += 1
return ansclass Solution {
public int minSelection(int[][] availableIntervals, int[][] targetIntervals) {
Arrays.sort(availableIntervals, (a, b) -> a[0] - b[0]);
Arrays.sort(targetIntervals, (a, b) -> a[0] - b[0]);
int ans = 0, cur = 0, i = 0;
for (int[] t : targetIntervals) {
int l = t[0], r = t[1];
while (cur < r) {
int uncover = Math.max(l, cur);
int nxt = cur;
while (i < availableIntervals.length && availableIntervals[i][0] <= uncover) {
nxt = Math.max(nxt, availableIntervals[i][1]);
i++;
}
if (nxt < uncover || nxt == cur) {
return -1;
}
cur = nxt;
ans++;
}
}
return ans;
}
}class Solution {
public:
int minSelection(vector<vector<int>>& availableIntervals, vector<vector<int>>& targetIntervals) {
sort(availableIntervals.begin(), availableIntervals.end(), [](auto& a, auto& b) { return a[0] < b[0]; });
sort(targetIntervals.begin(), targetIntervals.end(), [](auto& a, auto& b) { return a[0] < b[0]; });
int ans = 0, cur = 0, i = 0;
for (auto& t : targetIntervals) {
int l = t[0], r = t[1];
while (cur < r) {
int uncover = max(l, cur);
int nxt = cur;
while (i < (int) availableIntervals.size() && availableIntervals[i][0] <= uncover) {
nxt = max(nxt, availableIntervals[i][1]);
i++;
}
if (nxt < uncover || nxt == cur) {
return -1;
}
cur = nxt;
ans++;
}
}
return ans;
}
};function minSelection(availableIntervals: number[][], targetIntervals: number[][]): number {
availableIntervals.sort((a, b) => a[0] - b[0]);
targetIntervals.sort((a, b) => a[0] - b[0]);
let ans = 0,
cur = 0,
i = 0;
for (const [l, r] of targetIntervals) {
while (cur < r) {
const uncover = Math.max(l, cur);
let nxt = cur;
while (i < availableIntervals.length && availableIntervals[i][0] <= uncover) {
nxt = Math.max(nxt, availableIntervals[i][1]);
i++;
}
if (nxt < uncover || nxt === cur) {
return -1;
}
cur = nxt;
ans++;
}
}
return ans;
}func minSelection(availableIntervals [][]int, targetIntervals [][]int) int {
sort.Slice(availableIntervals, func(a, b int) bool { return availableIntervals[a][0] < availableIntervals[b][0] })
sort.Slice(targetIntervals, func(a, b int) bool { return targetIntervals[a][0] < targetIntervals[b][0] })
ans, cur, i := 0, 0, 0
for _, t := range targetIntervals {
l, r := t[0], t[1]
for cur < r {
uncover := max(l, cur)
nxt := cur
for i < len(availableIntervals) && availableIntervals[i][0] <= uncover {
nxt = max(nxt, availableIntervals[i][1])
i++
}
if nxt < uncover || nxt == cur {
return -1
}
cur = nxt
ans++
}
}
return ans
}Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Subset Search | O(2^n * m) | O(n) | Only to verify correctness on tiny inputs |
| Greedy Sort and Sweep | O(n log n + m log m) | O(n + m) | General case and interview answer |
| Heap-Based Selection | O(n log n + m log n) | O(n) | When eligibility rules are more complex than endpoint checks |
Frequently asked questions
Is Minimum Interval Selection to Cover Target Intervals easy or hard?
It is rated Hard, with a 30.8% acceptance rate. The difficulty comes from proving that the greedy choice of the farthest reaching candidate is optimal, not from the code itself, which is short once the sweep is clear.
Minimum Interval Selection to Cover Target Intervals Python or Java solution?
Both are straightforward. In Python, sort with key lambdas and use a simple while loop with a pointer. In Java, sort arrays with Arrays.sort using a comparator, and use PriorityQueue for the heap variant. Focus on the sort-and-sweep logic, since the language syntax is minor.
How to solve Minimum Interval Selection to Cover Target Intervals in O(n log n)?
Sort both lists, then use a pointer over the sorted candidates while iterating through the sorted targets. Keep track of the best right endpoint among candidates that start at or before the current target's left endpoint. When the current target is not yet reached by your chosen interval, select that best candidate and increment the count.
What is the best approach for Minimum Interval Selection to Cover Target Intervals?
The best approach is a greedy sort-and-sweep. Sort targets by right endpoint and candidates by left endpoint, then for each uncovered target pick the reachable candidate with the largest right endpoint. It runs in O(n log n + m log m) time and O(n + m) space.
What data structure is used in Minimum Interval Selection to Cover Target Intervals?
The greedy solution uses sorted arrays and a pointer. The heap-based variant uses a max-heap keyed by right endpoint to pick the candidate that reaches farthest. No complex tree structures are required.
What is the time complexity of Minimum Interval Selection to Cover Target Intervals?
The optimal greedy solution runs in O(n log n + m log m) time, dominated by sorting the candidate and target intervals. The brute force subset search is O(2^n * m) and is only practical for very small inputs.
Is Minimum Interval Selection to Cover Target Intervals asked at Google, Amazon, or Meta?
This problem is tagged as General on FleetCode, so no specific company frequency is confirmed. Interval covering and greedy sweep patterns appear often in interviews at large tech companies, so the technique is worth mastering regardless.
