Set Intersection Size At Least Two - Problem

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.

For example, if intervals = [[1,3], [3,7], [8,9]], then [1,2,4,7,8,9] and [2,3,4,8,9] are containing sets.

Return the minimum possible size of a containing set.

Input & Output

Example 1 — Basic Case
$ Input: intervals = [[1,3], [3,7], [8,9]]
Output: 5
💡 Note: We need a set where each interval has at least 2 numbers. One optimal set is [2,3,7,8,9]: interval [1,3] contains {2,3}, interval [3,7] contains {3,7}, interval [8,9] contains {8,9}.
Example 2 — Overlapping Intervals
$ Input: intervals = [[1,3], [1,4], [2,5], [3,5]]
Output: 3
💡 Note: One optimal set is [2,3,4]: all intervals contain at least 2 of these numbers.
Example 3 — Single Interval
$ Input: intervals = [[1,2]]
Output: 2
💡 Note: The interval [1,2] needs at least 2 numbers, so minimum set is [1,2].

Constraints

  • 1 ≤ intervals.length ≤ 3000
  • intervals[i].length == 2
  • 0 ≤ starti < endi ≤ 3000

Visualization

Tap to expand
Set Intersection Size At Least TwoFind minimum set where each interval contains at least 2 numbers[1,3][3,7][8,9]Interval 1Interval 2Interval 3Need: Each interval must contain ≥ 2 numbers from our setOptimal Set: [2, 3, 7, 8, 9][1,3]→{2,3} [3,7]→{3,7} [8,9]→{8,9}Minimum Size: 5
Understanding the Visualization
1
Input
Intervals that each need ≥2 numbers
2
Process
Find optimal set covering all intervals
3
Output
Minimum size of containing set
Key Takeaway
🎯 Key Insight: Sort by end points and greedily select rightmost numbers to maximize future coverage
Asked in
Google 25 Facebook 18 Microsoft 15
28.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen