DSA problem
Set Intersection Size At Least Two
You are given a 2D integer array intervals where intervals[i] = [start_i, end_i] represents all the integers from start_i to end_i inclusively. A containing set is an array nums where each interval from intervals has at least two integers in nums. Return the minimum possible size of a containing set.
A brute-force solution would try every subset of integers up to some bound — totally infeasible because the interval endpoints can be as large as 10^8. The right structure to exploit is the classic interval scheduling intuition: pick integers greedily to "cover" as many future intervals as possible.
The pivotal sort is by ascending end-point, ties by descending start-point. Why? Sorting by end-point lets us settle intervals one at a time in the order they "close out", which is exactly the standard greedy schedule. Ties broken by descending start-point ensure that wider intervals come first so any picked points from a wider interval are equally usable for the narrower sibling.
Maintain the two most recent picks p1 < p2 (the candidate integers we have committed to so far). For each interval [s, e] in sorted order, count how many of p1, p2 lie in [s, e]. If both lie inside, no new picks needed. If only p2 lies inside, add one new pick: p1 = p2; p2 = e. If neither lies inside, add two new picks: p1 = e - 1; p2 = e. Pick the largest legal values (e and e - 1) so they have the best chance of also covering subsequent intervals. The size of nums is the running count, returned at the end.
Examples
intervals = [[1,3],[3,7],[8,9]]5intervals = [[1,3],[1,4],[2,5],[3,5]]3intervals = [[1,2],[2,3],[2,4],[4,5]]5Constraints
- 1 <= intervals.length <= 3000
- intervals[i].length == 2
- 0 <= start_i < end_i <= 10^8
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.