-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a1c4f27
commit 9204ace
Showing
3 changed files
with
63 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
29 changes: 29 additions & 0 deletions
29
src/page-5/435. Non-overlapping Intervals/eraseOverlapIntervals.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import { eraseOverlapIntervals } from './eraseOverlapIntervals'; | ||
|
||
describe('435. Non-overlapping Intervals', () => { | ||
test('eraseOverlapIntervals', () => { | ||
expect( | ||
eraseOverlapIntervals([ | ||
[1, 2], | ||
[2, 3], | ||
[3, 4], | ||
[1, 3], | ||
]), | ||
).toBe(1); | ||
|
||
expect( | ||
eraseOverlapIntervals([ | ||
[1, 2], | ||
[1, 2], | ||
[1, 2], | ||
]), | ||
).toBe(2); | ||
|
||
expect( | ||
eraseOverlapIntervals([ | ||
[1, 2], | ||
[2, 3], | ||
]), | ||
).toBe(0); | ||
}); | ||
}); |
28 changes: 28 additions & 0 deletions
28
src/page-5/435. Non-overlapping Intervals/eraseOverlapIntervals.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
type EraseOverlapIntervals = (intervals: number[][]) => number; | ||
|
||
/** | ||
* Accepted | ||
*/ | ||
export const eraseOverlapIntervals: EraseOverlapIntervals = (intervals) => { | ||
// Step 1: Sort intervals by end time | ||
intervals.sort((a, b) => a[1] - b[1]); | ||
|
||
let removalCount = 0; | ||
let prevEnd = intervals[0][1]; // Initialize with the end time of the first interval | ||
|
||
// Step 2: Traverse the sorted intervals starting from the second interval | ||
for (let i = 1; i < intervals.length; i++) { | ||
const [start, end] = intervals[i]; | ||
|
||
// Step 3: Check for overlap | ||
if (start < prevEnd) { | ||
// Overlapping interval found, increment removal count | ||
removalCount += 1; | ||
} else { | ||
// Update `prevEnd` to the end of the current interval if there's no overlap | ||
prevEnd = end; | ||
} | ||
} | ||
|
||
return removalCount; | ||
}; |