Skip to content

4086. Minimum Interval Selection to Cover Target Intervals

SourceWeekly Contest 524 Q4DifficultyHardRating2202

Description

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 * 104
  • availableIntervals[i].length == targetIntervals[j].length == 2
  • 1 <= availableIntervals[i][0] <= availableIntervals[i][1] <= 105
  • 1 <= targetIntervals[j][0] <= targetIntervals[j][1] <= 105

Solutions

Solution 1: Sorting + Greedy

Thinking

Both arrays can contain \(5 \times 10^4\) intervals, so enumerating subsets cannot check that every real point of every target is covered. Coordinates only go up to \(10^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 \(\textit{cur}\), the next required point of target \([l, r]\) is \(\max(l, \textit{cur})\). Extend from \(\textit{cur}\) when that point lies inside the target. When \(l\) is 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 \(\textit{availableIntervals}\) and \(\textit{targetIntervals}\) by left endpoint. \(\textit{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 \(\textit{cur} \ge r\). Otherwise set \(\textit{uncover} = \max(l, \textit{cur})\), and let \(\textit{nxt}\) be the maximum right endpoint among available intervals whose left endpoint is at most \(\textit{uncover}\). If \(\textit{nxt} < \textit{uncover}\), no available interval contains that point. If \(\textit{nxt} = \textit{cur}\), coverage cannot move any farther right. Both cases return \(-1\). Otherwise select the interval with that farthest right endpoint, set \(\textit{cur} = \textit{nxt}\), and add \(1\) to the answer, until \(\textit{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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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 ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class 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;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;
}

Comments