Skip to content

Commit

Permalink
251st Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Shyam-Chen committed Nov 9, 2024
1 parent a1c4f27 commit 9204ace
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 4 deletions.
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -280,10 +280,12 @@ Ace Coding Interview with 75 Qs
[208]: ./src/page-2/208.%20Implement%20Trie%20(Prefix%20Tree)/Trie.ts
[1268]: ./src/page-12/1268.%20Search%20Suggestions%20System/suggestedProducts.ts

| Intervals | | |
| ----------------------------------------------- | -------- | ------ |
| 435. Non-overlapping Intervals | Solution | Medium |
| 452. Minimum Number of Arrows to Burst Balloons | Solution | Medium |
| Intervals | | |
| ----------------------------------------------- | --------------- | ------ |
| 435. Non-overlapping Intervals | [Solution][435] | Medium |
| 452. Minimum Number of Arrows to Burst Balloons | Solution | Medium |

[435]: ./src/page-5/435.%20Non-overlapping%20Intervals/eraseOverlapIntervals.ts

| Monotonic Stack | | |
| ----------------------- | -------- | ------ |
Expand Down
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 src/page-5/435. Non-overlapping Intervals/eraseOverlapIntervals.ts
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;
};

0 comments on commit 9204ace

Please sign in to comment.