# 56. Merge Intervals Leetcode Solution

## Merge Intervals Leetcode Problem :

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.

## Merge Intervals Leetcode Solution :

### Constraints :

• 1 <= intervals.length <= 10^4
• intervals[i].length == 2
• 0 <= start[i] <= end[i] <= 10^4

### Example 1:

• Input: intervals = [[1,4],[4,5]]
• Output: [[1,5]]

Intuition :

We need to sort and then check the consecutive intervals. Once we find the overlapping interval. we will take the max element from it.

Approach :

1. Firstly, the base case : if there are no intervals return [] .
2. Sort the intervals .
3. While traversing the intervals vector we will come accross two coditions
• First condition : if there is a overlapping between the intervals then just take out the max element from the ending point and thus we merged them
eg:- [1,4],[2,8] =Mergerd intervals will be> [1,8]
• second condition : if there is no overlapping then simply push those interval to our resultant vector .

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

## Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others