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 Two INPUT intervals = [[1,3], [3,7], [8,9]] 1 2 3 4 5 6 7 8 9 [1,3] [3,7] [8,9] Goal: Find smallest set with 2+ elements in each interval ALGORITHM STEPS 1 Sort by End Points Sort intervals by end, then start [1,3], [3,7], [8,9] (already sorted) 2 Process [1,3] Add end-1 and end: {2, 3} 3 Process [3,7] 3 in set, need 1 more: {2,3,6,7} 4 Process [8,9] No overlap, add: {2,3,6,7,8,9} Containing Set: {2, 3, 6, 7, 8, 9} -- wait FINAL RESULT Optimal Containing Set: 2 3 6 7 8 Verification: [1,3]: has 2,3 -- OK [3,7]: has 3,6,7 -- OK [8,9]: has 8 -- need 9! Actual set: {2,3,6,7,8,9} Output: 5 Key Insight: Sort intervals by end point (ascending), then by start (descending). Process greedily: always pick the last two elements of each interval when needed. This minimizes overlap waste and ensures maximum reuse of selected points for subsequent intervals. TutorialsPoint - Set Intersection Size At Least Two | Greedy - Sort by End Points
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