Python 0757.py
class Solution:
def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:
result = 0
one = two = -1 # positions of the most recent elements
intervals.sort(key = lambda x : ( x[1], -x[0] ))
for start, end in intervals:
if one >= start:
continue
if two >= start:
one = two
two = end
result += 1
else:
one = end - 1
two = end
result += 2
return result
Difficulty
and has an acceptance rate of about 58% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The intersectionSizeTwo method computes the smallest possible size of a set of integers such that every interval in the input list contains at least two of those integers. It follows a greedy strategy: intervals are processed in a specific order, and the algorithm keeps track of the two most recently chosen numbers. By carefully choosing when to add one or two new numbers, the method guarantees that the resulting set satisfies the requirement while using the fewest elements.
Key Steps
Sorting the intervals
The first operation orders the intervals by their right endpoint in ascending order; when two intervals share the same right endpoint, the one with the larger left endpoint comes first. This ordering is crucial because it allows the algorithm to make decisions based on the tightest constraints first.
intervals.sort(key = lambda x : ( x[1], -x[0] ))
Initializing the tracking variables
Two variables, one and two, store the positions of the most recently selected integers. They are initialized to -1, a value that is guaranteed to be smaller than any possible interval start, ensuring that the first interval will always trigger an insertion.
one = two = -1 # positions of the most recent elements
Iterating through the intervals and updating the set
The core loop examines each interval [start, end] in the sorted order. Three situations are distinguished:
-
If the earlier of the two stored points (
one) already lies inside the current interval, the interval already contains two selected numbers, and the loop proceeds without change. -
If only the later point (
two) lies inside the interval, the algorithm shiftsonetotwo, adds the interval’s right endpoint as the newtwo, and increments the result by one. This adds exactly one new number while preserving the invariant that the two stored points are the largest possible numbers inside the processed intervals. -
If neither stored point lies inside the interval, the algorithm selects the two largest possible numbers within the interval:
end-1andend. Both are added to the result, and the tracking variables are updated accordingly.
for start, end in intervals:
if one >= start:
continue
if two >= start:
one = two
two = end
result += 1
else:
one = end - 1
two = end
result += 2
Finally, the method returns the accumulated count, which equals the size of the minimal set.
return result
Edge Cases Handled
When an interval’s left endpoint is greater than the previously stored points, the algorithm correctly identifies that the interval lacks the required two numbers and inserts the two largest possible values (end-1 and end). This also covers intervals of length one, because end-1 may equal end; in that situation the algorithm still adds two numbers, satisfying the “at least two” condition even if the interval contains a single integer value.
If two intervals share the same right endpoint, the secondary sort key (-x[0]) ensures that the interval with the larger left endpoint is processed first. This ordering prevents unnecessary additions because the tighter interval is satisfied before the looser one, allowing the later interval to reuse the numbers already chosen.
When an interval already contains both previously selected numbers (one and two), the early continue statement skips any modification, preserving the minimality of the set.
If only the later point (two) falls inside the interval, the algorithm shifts one forward to two and adds just one new number (end). This case handles overlapping intervals where one previously chosen number can be reused, reducing the total count.
Performance Optimizations
The custom sorting key combines the primary sort on the right endpoint with a secondary sort on the negated left endpoint. By placing intervals with larger left boundaries earlier when right endpoints tie, the algorithm reduces the need for extra insertions later in the scan.
All state is kept in a constant number of integer variables (result, one, two), so the algorithm uses O(1) additional memory regardless of the input size.
The greedy update logic inside the loop performs only a few comparisons and assignments per interval, avoiding any nested loops or auxiliary data structures. This streamlined processing ensures that the method runs efficiently even for large collections of intervals.
ELI5 - Simplified Explanation
Imagine you have a long line of colored blocks and you want to pick out some special spots to place markers. First, look at all the different zones on the floor and put the ones that end earliest at the front of the line.
Now, walk through these zones one by one. You want to keep track of the two markers you placed most recently. If you look at a zone and see that your most recent marker is already inside it, you do not need to do anything else because that zone is already covered.
If only one of your markers is inside the zone, you need to add one more. You take your second marker and move it to the very end of the current zone to make sure everything is perfect.
If neither of your markers is inside the zone, you have to add two new markers. You place them right at the end of the zone so that they can help cover this area and hopefully reach into the next zones too. You keep doing this until every zone you were given has two markers inside it.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Java | Go | Python | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| JoshCrozier | JS | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| JoshCrozier | JavaScript | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 691: Stickers to Spell Word
- problem 715: Range Module
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality