Skip to main content

Merge Intervals

KANISHKA GUPTA
EditReport

Merge Intervals

Problem Statement​

Given a collection of intervals, merge all overlapping intervals.

Video Explanation​

Approach​

To merge the intervals, we can first sort them based on the start time. Then, we can iterate through the sorted intervals and merge them as needed.

Steps:​

  1. Initialize : Sort:

    • Sort the intervals by their start times.
    • Initialize a list to hold the merged intervals.
  2. Iterate:

    • For each interval, check if it overlaps with the last merged interval.
    • If it does, merge them. If not, add the interval to the list.
  3. Return:

    • Return the merged intervals.

Solutions​

class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if (intervals.empty()) return {};
sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
for (const auto& interval : intervals) {
if (merged.empty() || merged.back()[1] < interval[0]) {
merged.push_back(interval);
} else {
merged.back()[1] = max(merged.back()[1], interval[1]);
}
}
return merged;
}
};
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

Was this page helpful?

💬

Discuss this page

Have a question or spot something confusing in "Merge Intervals"? Ask below. Backed by GitHub Discussions—maintainers receive system notifications directly.