Skip to content

Commit 0cbbd19

Browse files
committed
Add non-overlapping-intervals solution
1 parent 92faf65 commit 0cbbd19

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

non-overlapping-intervals/Jeehay28.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// 🚀 Greedy Algorithm
2+
// ✅ Time Complexity: O(n log n), where n is the number of intervals
3+
// - Sorting the intervals: O(n log n)
4+
// - Iterating through intervals: O(n)
5+
6+
// ✅ Space Complexity: O(1), No other data structures are used,
7+
8+
/**
9+
* @param {number[][]} intervals
10+
* @return {number}
11+
*/
12+
var eraseOverlapIntervals = function (intervals) {
13+
// ✅ Sorting by end time ensures that we keep intervals that finish the earliest, reducing the chances of overlap with the subsequent intervals.
14+
// ❌ Sorting by start time would lead to a greedy choice too early, causing unnecessary removals.
15+
intervals.sort((a, b) => a[1] - b[1]);
16+
17+
let removalCnt = 0;
18+
19+
let prevEnd = intervals[0][1];
20+
21+
for (let i = 1; i < intervals.length; i++) {
22+
const [start, end] = intervals[i];
23+
24+
if (start < prevEnd) {
25+
removalCnt += 1; // Increment removal count for an overlap
26+
} else {
27+
prevEnd = end;
28+
}
29+
}
30+
return removalCnt;
31+
};
32+

0 commit comments

Comments
 (0)