Merge Intervals
The problem
You are given an array intervals where intervals[i] = [startᵢ, endᵢ] represents the inclusive interval startᵢ ≤ x ≤ endᵢ.
Your task is to merge every pair of intervals that overlap and return all the non-overlapping intervals that completely cover the same ranges as the original array. Two intervals overlap if they share at least one common point (i.e. start₂ ≤ end₁ and start₁ ≤ end₂).
Return the merged intervals in any order.
**Input: **intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] **Explanation: **[1,3] and [2,6] overlap --> merge to [1,6].
Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Because the end of [1,4] equals the start of [4,5], they are considered overlapping.
Input: intervals = [[1,4],[5,6]]
- 1 ≤ intervals.length ≤ 10⁴
- intervals[i].length == 2
- 0 ≤ startᵢ ≤ endᵢ ≤ 10⁴
cpp
class Solution {
public:
vector<vector<int>> mergeIntervals(vector<vector<int>>& intervals) {
// Your code goes here
}
};java
class Solution {
public List<List<Integer>> merge(List<List<Integer>> intervals) {
// Your code goes here
}
}python
class Solution:
def merge(self, intervals):
# Your code goes herejavascript
class Solution {
merge(intervals) {
// Your code goes here
}
}csharp
public class Solution {
public IList<IList<int>> Merge(IList<IList<int>> intervals) {
// Your code goes here
}
}go
func mergeIntervals(intervals [][]int) [][]intStuck? Show a way to structure it+
- 01Sort by start, then scan left to right.
- 02Keep the last merged interval as the active range.
- 03Extend it when the next start is within its end.
- 04Otherwise emit it and begin a new range.
Reference answer
Then expect these follow-ups
How would you merge intervals arriving as a stream?
Tests: online algorithms
How do you insert one interval into an already merged list?
Tests: two-pointer scan
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question
- Calculate the trapped rainwater between bars in a given array.
- Find a triplet in an array with a given sum.
- Print all combinations of numbers from 1 to n that sum to n.
- Find the number of rotations in a circularly sorted array.
- Find all permutations of a given string.
- Check if two given binary trees are identical.