Interval List Intersections LeetCode solution in JavaScript

1
var intervalIntersection = function (firstList, secondList) {
2
//if a overlap b - a.start >= b.start && a.start <= b.end
3
//if b overlap a - b.start >= a.start && b.start <= a.end
4

5
//handle empty edge cases
6
if (firstList.length === 0 || secondList.length === 0) {
7
return [];
8
}
9

10
let merged = [];
11
let i = 0;
12
let j = 0;
13
while (i < firstList.length && j < secondList.length) {
14
let a_overlap_b =
15
firstList[i][0] >= secondList[j][0] &&
16
firstList[i][0] <= secondList[j][1];
17
let b_overlap_a =
18
secondList[j][0] >= firstList[i][0] &&
19
secondList[j][0] <= firstList[i][1];
20

21
if (a_overlap_b || b_overlap_a) {
22
let start = Math.max(firstList[i][0], secondList[j][0]);
23
let end = Math.min(firstList[i][1], secondList[j][1]);
24
merged.push([start, end]);
25
}
26

27
if (firstList[i][1] < secondList[j][1]) {
28
i++;
29
} else {
30
j++;
31
}
32
}
33

34
return merged;
35
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0