Set Intersection Size At Least Two - Problem

You're tasked with finding the minimum number of integers that can cover multiple intervals with a special constraint: each interval must contain at least two of your chosen integers.

Given a 2D array intervals where intervals[i] = [start_i, end_i] represents all integers from start_i to end_i inclusively, you need to create a containing set - an array of numbers where each interval has at least two integers from your set.

Example: If intervals = [[1,3], [3,7], [8,9]], then [1,2,4,7,8,9] and [2,3,4,8,9] are both valid containing sets, but [2,3,4,8,9] is smaller with only 5 elements.

Your goal is to return the minimum possible size of such a containing set. This is a classic optimization problem that tests your understanding of greedy algorithms and interval scheduling.

Input & Output

example_1.py โ€” Basic Case
$ Input: intervals = [[1,3], [3,7], [8,9]]
โ€บ Output: 5
๐Ÿ’ก Note: We need at least 2 integers in each interval. One optimal solution is [2,3,7,8,9]: interval [1,3] contains {2,3}, interval [3,7] contains {3,7}, and interval [8,9] contains {8,9}.
example_2.py โ€” Overlapping Intervals
$ Input: intervals = [[1,2], [2,3], [2,4], [4,5]]
โ€บ Output: 5
๐Ÿ’ก Note: The optimal solution is [1,2,3,4,5]. Each interval needs exactly 2 numbers, and due to minimal overlap, we need most numbers individually.
example_3.py โ€” Highly Overlapping
$ Input: intervals = [[1,5], [2,4], [3,6]]
โ€บ Output: 3
๐Ÿ’ก Note: We can use [3,4,5] or [4,5,6]. All intervals [1,5], [2,4], [3,6] will contain at least 2 of these numbers due to high overlap.

Constraints

  • 1 โ‰ค intervals.length โ‰ค 3000
  • intervals[i].length == 2
  • 0 โ‰ค starti < endi โ‰ค 1000
  • Each interval must contain at least 2 integers from the result set

Visualization

Tap to expand
Security Guard Placement OptimizationBuilding LayoutSection A [1-3]Section B [3-7]Section C [8-9]G1G2G3G4G5Optimal Solution: 5 Guards TotalEach section covered by at least 2 guards
Understanding the Visualization
1
Sort Sections
Arrange building sections by their end positions to process systematically
2
Greedy Placement
For each section, place guards as far right as possible to maximize future coverage
3
Check Coverage
Verify each section has at least 2 guards, add more if needed
4
Optimal Result
This greedy approach guarantees minimum total guards needed
Key Takeaway
๐ŸŽฏ Key Insight: Greedy placement at rightmost positions maximizes coverage efficiency while ensuring every interval gets its required minimum of 2 points.
Asked in
Google 45 Amazon 32 Microsoft 28 Meta 19
27.2K Views
Medium Frequency
~35 min Avg. Time
892 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