# Inserting a new interval in a sorted array of intervals in JavaScript

JavascriptWeb DevelopmentFront End Technology

For the purpose of this question, we define an interval as an array of two numbers where the first number is always smaller than the second number.

For example −

[4, 6], [2, 3], [6, 8], [2, 7], [1, 8] are all examples of valid intervals.

Suppose, we have an array of intervals which is sorted according to the their start times (the first elements of each interval).

The intervals in the array are non-overlapping which means that for any two arbitrary adjacent intervals,

[m, n], [x, y]
m < n < x < y

Therefore, one such example of this array of intervals can be −

const arr = [[ 2, 4], [5, 7], [9, 10], [13, 17]];

We are required to write a JavaScript function that takes in one such array of intervals as the first argument and a single interval as the second argument.

The function should then insert the interval at its correct position in the array, maintain the nonoverlapping property of the array.

If required we can merge two or more intervals in the array in order to keep the array intervals non-overlapping.

For example, if for the above array of intervals, the interval we need to insert is [6, 13] Then the output should look like −

const output = [[2, 4], [5, 17]];

## Example

Following is the code −

const arr = [[2, 4], [5, 7], [9, 10], [13, 17]];
const interval = [6, 13];
const insertWithin = (arr = [], interval = []) => {
const res = [];
let ind = 0;
while (arr[ind] && arr[ind][1] < interval[0]) {
res.push(arr[ind]);
++ind;
};
let start = interval[0];
let end = interval[1];
while (arr[ind] && arr[ind][0] <= interval[1]) {
start = Math.min(start, arr[ind][0]);
end = Math.max(end, arr[ind][1]);
++ind;
}
res.push([start, end]);
while (arr[ind]) {
res.push(arr[ind]);
++ind;
}
return res;
};
console.log(insertWithin(arr, interval));

## Output

Following is the console output −

[[2, 4], [5, 17]]
Published on 18-Jan-2021 04:53:02