Skip to content

Instantly share code, notes, and snippets.

@MohammedALREAI
Created April 19, 2021 20:50
Show Gist options
  • Select an option

  • Save MohammedALREAI/2cceeaba7da631a60815196793790592 to your computer and use it in GitHub Desktop.

Select an option

Save MohammedALREAI/2cceeaba7da631a60815196793790592 to your computer and use it in GitHub Desktop.
57. Insert Interval
function insert(intervals: number[][], newInterval: number[]): number[][] {
let i = 0;
while (i < intervals.length) {
const [a, b] = intervals[i];
const [c, d] = newInterval;
if (
(a >= c && a <= d) ||
(b >= c && b <= d) ||
(c >= a && c <= b) ||
(d >= a && d <= b)
) {
newInterval = mergeIntervals(intervals[i], newInterval);
intervals.splice(i, 1);
} else {
i++;
}
}
intervals.push(newInterval);
intervals.sort((a, b) => a[0] - b[0]);
return intervals;
}
const mergeIntervals = (int1: number[], int2: number[]) => [
Math.min(int1[0], int2[0]),
Math.max(int1[1], int2[1]),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment