File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
non-overlapping-intervals Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments