01
Merge overlaps (Intervals Sub-pattern)
Sort by start and build the answer left to right. Each interval either extends the last merged block or starts a new one.
Signals in the problem statement
- ›
"merge all overlapping intervals"
- ›
"insert a new interval and merge if needed"
- ›
"remove intervals covered by another one"
- ›
"count the days not covered by any meeting"
What makes it different
Merge Intervals is the template. Insert Interval is already sorted, so skip the sort: copy what ends before, absorb what overlaps, copy the rest — O(N). Remove Covered Intervals sorts by start, and on equal starts by end descending, so the bigger interval comes first and covers the smaller. Count Days Without Meetings merges, then subtracts the covered days from the total (end − start + 1 each, since days are inclusive).
Questions
ordered from “learn the idea” to “recognise it without help”- 1Merge IntervalsWalkthroughMediumBasic Anchor·LeetCode #56
- 2Insert IntervalWalkthroughMediumBasic Reinforcement·LeetCode #57
- 3Remove Covered IntervalsWalkthroughMediumSlight Variation·LeetCode #1288
- 4Count Days Without MeetingsWalkthroughMediumPattern Transfer·LeetCode #3169
Template
merge-template.cpp
// Merge Intervals: sort by start, then extend the last merged block or start a new one.
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end()); // by start (then end)
vector<vector<int>> res;
for (auto& cur : intervals) {
if (!res.empty() && cur[0] <= res.back()[1]) // overlaps the LAST merged block
res.back()[1] = max(res.back()[1], cur[1]); // max: cur may sit inside it
else
res.push_back(cur); // gap → new block
}
return res;
}Remember this · Intervals
Trigger
Input is [start, end] pairs; overlap, merge, insert, meeting rooms, free time, minimum removals.
Think
After sorting, do I only ever need to compare against the most recent interval?
Key question
Sort by start or by end — which one makes the greedy choice obvious?