Intervals · Pattern 1 of 3
Interval basics: overlap, merge, intersect and greedy
Sort by start, then compare each interval with the last one you kept: extend it if they overlap, start a new one if not. Sort by end instead when you want to keep as many intervals as possible.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Merge overlapping ranges, or insert one into a sorted list
- Can one person attend every meeting? Does a new booking clash?
- The fewest removals (or arrows) so that nothing overlaps
- The common part of two lists of ranges
The template
// merge overlapping intervals: sort by start, extend the last kept one
int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> res = new ArrayList<>();
for (int[] cur : intervals) {
int[] last = res.isEmpty() ? null : res.get(res.size() - 1);
if (last != null && cur[0] <= last[1]) last[1] = Math.max(last[1], cur[1]); // overlaps: extend
else res.add(new int[]{cur[0], cur[1]}); // gap: new interval
}
return res.toArray(new int[0][]);
}
// fewest removals so the rest do not overlap: greedily keep the one that ends first
int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
int kept = 0;
long end = Long.MIN_VALUE;
for (int[] iv : intervals) {
if (iv[0] >= end) { kept++; end = iv[1]; } // touching is allowed here
}
return intervals.length - kept;
} def merge(intervals):
intervals.sort(key=lambda x: x[0]) # sort by start
res = []
for s, e in intervals:
if res and s <= res[-1][1]:
res[-1][1] = max(res[-1][1], e) # overlaps: extend
else:
res.append([s, e]) # gap: new interval
return res
def erase_overlap_intervals(intervals):
intervals.sort(key=lambda x: x[1]) # sort by end: keep the one that ends first
kept, end = 0, float('-inf')
for s, e in intervals:
if s >= end: # touching is allowed here
kept += 1
end = e
return len(intervals) - kept // merge overlapping intervals: sort by start, extend the last kept one
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> res;
for (auto& cur : intervals) {
if (!res.empty() && cur[0] <= res.back()[1]) res.back()[1] = max(res.back()[1], cur[1]);
else res.push_back(cur); // gap: new interval
}
return res;
}
// fewest removals so the rest do not overlap: greedily keep the one that ends first
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), [](auto& a, auto& b) { return a[1] < b[1]; });
int kept = 0;
long long end = LLONG_MIN;
for (auto& iv : intervals) {
if (iv[0] >= end) { kept++; end = iv[1]; } // touching is allowed here
}
return (int)intervals.size() - kept;
} // merge overlapping intervals: sort by start, extend the last kept one
function merge(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const res = [];
for (const [s, e] of intervals) {
const last = res[res.length - 1];
if (last && s <= last[1]) last[1] = Math.max(last[1], e); // overlaps: extend
else res.push([s, e]); // gap: new interval
}
return res;
}
// fewest removals so the rest do not overlap: greedily keep the one that ends first
function eraseOverlapIntervals(intervals) {
intervals.sort((a, b) => a[1] - b[1]);
let kept = 0, end = -Infinity;
for (const [s, e] of intervals) {
if (s >= end) { kept++; end = e; } // touching is allowed here
}
return intervals.length - kept;
} The variations
-
1Merge overlapping intervals
Sort by start and keep a result list. If the next interval starts at or before the last kept end, extend that end with
max; otherwise push it. Inserting into an already sorted list needs no sort: copy what ends before, merge what overlaps, copy the rest. Partition labels is a merge too: each letter spans from its first to its last position.Now you solve- Insert Interval Medium Stuck? solution
- Count Days Without Meetings Medium Stuck? solution
- Partition Labels Medium Stuck? solution
-
2Intersect two sorted lists
Two pointers, one per list. The common part of the two current intervals is
[max(starts), min(ends)]when that is not empty. Then move the pointer whose interval ends first, because it cannot meet anything else. -
3Detect a conflict
After sorting by start, there is a clash exactly when some interval starts before the previous one ends. For bookings that arrive one at a time, check the new one against the booking just before it and just after it (a sorted map makes that O(log n)).
Now you solve- My Calendar I Medium Stuck? solution
-
4Greedy by end time
To keep the most intervals that do not overlap, always keep the one that ends first: it leaves the most room for the rest. Removals are n minus what you kept. The fewest arrows for balloons is the same count, with closed intervals.
Now you solve -
5Best pair that does not overlap
Sort by start and walk forward. Keep a min-heap of earlier events by end time; pop every event that ended before the current start and remember the best value among them. Current value plus that best is a candidate answer.
Mistakes to avoid
- Merging without sorting first:
[[2, 6], [1, 3]]then merges into[2, 6]and loses the part from 1 to 2 (sorted, the answer is[1, 6]). - Greedy removal sorted by start: one long interval that starts early blocks many short ones. Sort by end.
- Balloons use closed intervals (an arrow at x = 2 bursts
[1, 2]and[2, 3]), unlike non-overlapping intervals where touching is fine. Check>vs>=.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.