## Algorithm

Problem Name: 435. Non-overlapping Intervals

Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Example 1:

```Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.
```

Example 2:

```Input: intervals = [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.
```

Example 3:

```Input: intervals = [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
```

Constraints:

• `1 <= intervals.length <= 105`
• `intervals[i].length == 2`
• `-5 * 104 <= starti < endi <= 5 * 104`

## Code Examples

### #1 Code Example with C++ Programming

```Code - C++ Programming```

``````
class Solution {
public:
int eraseOverlapIntervals(vector& intervals) {
sort(intervals.begin(), intervals.end(), [](Interval& a, Interval& b){ return a.start < b.start; });
int count = 0;
for(int i = 1,  j = 0; i < intervals.size(); i++){
int pre = i;
if(intervals[i].start < intervals[j].end){
count++;
if(intervals[i].end > intervals[j].end) pre = j;
}
j = pre;
}
return count;
}
};
``````
Copy The Code &

Input

cmd
intervals = [[1,2],[2,3],[3,4],[1,3]]

Output

cmd
1

### #2 Code Example with Java Programming

```Code - Java Programming```

``````
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
if (intervals.length == 0) {
return 0;
}
Arrays.sort(intervals, Comparator.comparingInt(o -> o));
int notRemoved = 1;
int end = intervals;
for (int i = 1; i < intervals.length; i++) {
if (intervals[i] >= end) {
notRemoved++;
end = intervals[i];
}
}
return intervals.length - notRemoved;
}
}
``````
Copy The Code &

Input

cmd
intervals = [[1,2],[2,3],[3,4],[1,3]]

Output

cmd
1

### #3 Code Example with Javascript Programming

```Code - Javascript Programming```

``````
const eraseOverlapIntervals = function(intervals) {
if(intervals == null || intervals.length === 0) return 0
intervals.sort((a, b) => a - b)
let res = 1, end = intervals
const len = intervals.length
for(let i = 1; i < len; i++) {
if(intervals[i] >= end) {
end = intervals[i]
res++
}
}

return len - res
};
``````
Copy The Code &

Input

cmd
intervals = [[1,2],[1,2],[1,2]]

Output

cmd
2

### #4 Code Example with Python Programming

```Code - Python Programming```

``````
class Solution:
def eraseOverlapIntervals(self, intervals):
intervals.sort(key = lambda x: x.end); res, curr = 0, -float("inf")
for i in intervals:
if curr > i.start: res += 1
else: curr = i.end
return res
``````
Copy The Code &

Input

cmd
intervals = [[1,2],[1,2],[1,2]]

Output

cmd
2