Problem 757 · LeetCode 757(opens in a new tab)
Set Intersection Size At Least Two
HardGreedy algorithms
You get a list intervals, where intervals[i] = [start, end] stands for every whole number from start to end, both ends included.
Choose a set of whole numbers so that each interval holds at least two of the chosen numbers. Return the smallest size such a set can have.
Example 1
Input: intervals = [[3,6],[1,4],[5,9],[2,3]]
Output: 4
Why: {2, 3, 6, 9}: [2,3] needs both 2 and 3, and [5,9] shares none of them2 more examples and the constraints
Example 2
Input: intervals = [[0,4],[1,5],[2,6]] Output: 2 Why: 3 and 4 lie in all three intervals
Example 3
Input: intervals = [[0,1],[1,2],[2,3]] Output: 4 Why: each interval has only two numbers, so all of 0, 1, 2, 3 are needed
Constraints
- 1 ≤ intervals.length ≤ 3,000
- intervals[i].length = 2
- 0 ≤ start < end ≤ 100,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Greedy, counting by scanO(n²)
- Track the two largest pointsO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 3,000 intervals | Verdict |
|---|---|---|---|
| Greedy, counting by scan | O(n²) | Passes; scans every point | |
| Track the two largest points | O(n log n) | Best; one check each |
n = number of intervals.
Edge cases to test
- One interval. [[4,9]] needs exactly 2 points.
- Intervals of length one. [[0,1],[1,2],[2,3]]: each has only two numbers, so every number is used.
- Shared ends. [[0,5],[3,5],[4,5]] all end at 5; 4 and 5 serve all of them, the answer is 2.
- Nested intervals. A wide interval around a narrow one is served by the narrow one's points.
- Disjoint intervals. No sharing at all: the answer is 2 × n.
Common mistakes
- Sorting by start instead of end, which picks points the later intervals cannot use.
- Breaking end ties by start ascending, which can count the same point twice.
- Picking the smallest points of an interval instead of its largest.
How to talk through it
- 1Clarify. Are the intervals inclusive? Are the chosen numbers whole numbers? Must they be distinct?
- 2Find the greedy. The interval that ends first should get its largest points; later ones end further right.
- 3Fix the order. Sort by end, and by start descending on ties.
- 4Shrink the state. Only the two largest picked points matter, so keep a and b instead of a list.
- 5Test out loud. Run a nested case, a chain of length-one intervals, and a set with shared ends.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?