# Merge Intervals LeetCode Solution

Here, We see Merge Intervals LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

# List of all LeetCode Solution

## Problem Statement

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals and return an array of the non-overlapping intervals that cover all the intervals in the input.

```Example 1:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].

Example 2:

Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
```

## Merge Intervals Solution C++

``````class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if(intervals.size()<=1) return intervals;
sort(intervals.begin(), intervals.end());
vector<vector<int>> output;
output.push_back(intervals[0]);
for(int i=1; i<intervals.size(); i++) {
if(output.back()[1] >= intervals[i][0]) output.back()[1] = max(output.back()[1] , intervals[i][1]);
else output.push_back(intervals[i]);
}
return output;
}
};```Code language: C++ (cpp)```

## Merge Intervals Solution Java

``````class Solution {
public int[][] merge(int[][] intervals) {
if(intervals == null || intervals.length == 0)
return intervals;
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
LinkedList<int[]> mergedIntervals = new LinkedList<>();
for(int[] curr : intervals) {
if(mergedIntervals.isEmpty() || mergedIntervals.getLast()[1] < curr[0])
mergedIntervals.add(curr);
else
mergedIntervals.getLast()[1] = Math.max(mergedIntervals.getLast()[1], curr[1]);
}
return mergedIntervals.toArray(new int[0][]);
}
}
```Code language: Java (java)```

## Merge Intervals Solution JavaScript

``````var merge = function(intervals) {
if(!intervals.length) return [];
intervals.sort((a, b) => a[0] - b[0]);

const result = [intervals[0]];

for(let [start, end] of intervals) {
const endPrev = result.at(-1)[1]
if(start <= endPrev) result.at(-1)[1] = Math.max(end, endPrev);
else result.push([start, end]);
}
return result;
};
```Code language: JavaScript (javascript)```

## Merge Intervals Solution Python

``````class Solution(object):
def merge(self, intervals):
START, END = 0, 1
result = []
intervals.sort( key = lambda x: (x[START], x[END] ) )
for interval in intervals:
if not result or ( result[-1][END] < interval[START] ):
result.append( interval )
else:
result[-1][END] = max(result[-1][END], interval[END])
return result```Code language: Python (python)```
Scroll to Top