Skip to content

Commit 58c09da

Browse files
add: delete-overlapping-intervals
1 parent 151f05c commit 58c09da

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# JavaScript Assessments
22

33
- [Convert string to group](convert-string-to-group)
4+
- [Delete Overlapping Intervals](delete-overlapping-intervals)
45
- [Filling all the missed angle brackets](filling-all-the-missed-angle-brackets)
56
- [Finding all the anagrams](finding-all-the-anagrams)
67
- [Finding the maximum depth of a binary tree](finding-the-maximum-depth-of-a-binary-tree)
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Delete Overlapping Intervals
2+
3+
You are given a two-dimensional array `intervals`, as an argument.
4+
Each element of `intervals` represent an arbitrary interval, such as `[start, end]`.
5+
There are overlapping intervals in `intervals` and you need to combine the intervals so that they do not overlap.
6+
7+
More specifically, the overlapping intervals are like below:
8+
9+
```javascript
10+
intervals = [
11+
[1, 3],
12+
[2, 4],
13+
[5, 7],
14+
];
15+
```
16+
17+
In this example, `[1, 3]` which is `intervals[0]` and `[2, 4]` which is `intervals[1]` are overlapping intervals.
18+
By combining `intervals[0]` and `intervals[1]`, you can get `[1, 4]`.
19+
20+
So output will be like below:
21+
22+
```console
23+
[ [1, 4], [5, 7] ]
24+
```
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
const sortIntervals = ([aStart, aEnd], [bStart, bEnd]) =>
2+
aStart > bStart || (aStart === bStart && aEnd > bEnd)
3+
? 1
4+
: -1;
5+
6+
const doIntersect = ([aStart, aEnd], [bStart, bEnd]) =>
7+
aStart <= bEnd && aEnd >= bStart;
8+
9+
const combineIntervals = (
10+
[aStart, aEnd],
11+
[bStart, bEnd],
12+
) => [Math.min(aStart, bStart), Math.max(aEnd, bEnd)];
13+
14+
const solution = (intervals) =>
15+
intervals
16+
.sort(sortIntervals)
17+
.reduce(
18+
(merged, currentSeg) =>
19+
merged.some((seg) => doIntersect(seg, currentSeg))
20+
? merged.map((seg) =>
21+
doIntersect(seg, currentSeg)
22+
? combineIntervals(seg, currentSeg)
23+
: seg,
24+
)
25+
: [...merged, currentSeg],
26+
[],
27+
);
28+
29+
(() => {
30+
console.log(
31+
solution([
32+
[2, 4],
33+
[9, 13],
34+
[3, 5],
35+
[1, 3],
36+
[5, 7],
37+
[1, 2],
38+
]),
39+
);
40+
})();

0 commit comments

Comments
 (0)