ZeeshanAli-0704

Posted on

Merge Array Interval

Approach to solve these types of question:

let say suppose we have two data
let A = [1,3]
let B = [2,4]

Now if we have to check if these two overlaps or not we can do the following

1) lets say MaxValue = take the Max of A[0] & B[0] i.e Max of [1] [2] is 2
2) lets say MinValue = take the Min of A[1] & B[1] i.e Min of [3] [4] is 3

Now compare MaxValue & MinValue

``````
if (MaxValue <= MinValue) {
// overlaps
return true;
} else {
// no overlaps
return false;
}

``````

Suppose you have array of intervals example

``````let intervals =[
[1, 3],
[2, 6],
[8, 10],
[15, 18],
];
``````

we can sort interval first & then can do the merging

`````` `intervals.sort((a, b) => a[0] - b[0]);`
``````
``````/**
* @param {number[][]} intervals
* @param {number[]} newInterval
* @return {number[][]}
*/
/**
* @param {number[][]} intervals
* @param {number[]} newInterval
* @return {number[][]}
*/
var insert = function(intervals, newInterval) {
const result = [];

for (let i = 0; i < intervals.length; i++) {
let interval = intervals[i];

// If overlaps
if (Math.max(interval[0], newInterval[0]) <= Math.min(interval[1], newInterval[1])) {
newInterval = [Math.min(interval[0], newInterval[0]), Math.max(interval[1], newInterval[1])];
continue;
}

// If lower
if (interval[0] > newInterval[1]) {
result.push(newInterval, ...intervals.slice(i));
return result;
}

result.push(interval);
}

result.push(newInterval);
return result;
};
``````
``````/**
* @param {number[][]} intervals
* @return {number[][]}
*/
var merge = function (intervals) {
let next = [];
let j = 0;
intervals.sort((a, b) => a[0] - b[0]);
next.push(intervals.shift());

for (let i = 0; i < intervals.length; i++) {
let currentInterval = intervals[i];
if (next[j][1] >= currentInterval[0]) {
next[j] = [next[j][0], Math.max(next[j][1], currentInterval[1])];
} else {
next.push(currentInterval);
j++;
}
}
return next;
};

``````
``````/**
* @param {number[][]} intervals
* @return {number}
*/
var removeCoveredIntervals = function(intervals) {
let next = [];
let j = 0;
intervals.sort((a, b) => a[0] - b[0]);
next.push(intervals.shift());

for (let i = 0; i < intervals.length; i++) {
let currentInterval = intervals[i];
if (next[j][0] <= currentInterval[0] && currentInterval[1] <= next[j][1]) {
next[j] = [next[j][0], next[j][1]];
} else if (
next[j][0] >= currentInterval[0] &&
currentInterval[1] >= next[j][1]
) {
next[j] = [currentInterval[0], currentInterval[1]];
} else {
next.push(currentInterval);
j++;
}
}
return next.length;
};
``````