Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Finding Intersection of Arrays of Intervals in JavaScript



Problem

JavaScript function that takes in two arrays, arr1 and arr2 of intervals which are pairwise disjoint and in sorted order.

A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b.

The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].) Our function is supposed to return the intersection of these two interval arrays.

For example, if the input to the function is −

const arr1 = [[0,2],[5,10],[13,23],[24,25]];
const arr2 = [[1,5],[8,12],[15,24],[25,26]];

Then the output should be −

const output = [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]];

Example

The code for this will be −

 Live Demo

const arr1 = [[0,2],[5,10],[13,23],[24,25]];
const arr2 = [[1,5],[8,12],[15,24],[25,26]];
const findIntersection = function (A, B) {
   const res = []
   let i = 0
   let j = 0
   while (i < A.length && j < B.length) {
      const [a, b] = A[i]
      const [c, d] = B[j]
      const lo = Math.max(a, c)
      const hi = Math.min(b, d)
      if (lo <= hi) {
         res.push([Math.max(a, c), Math.min(b, d)])
      }
      if (b < d) {
         i++
      } else {
         j++
      }
   }
   return res
};
console.log(findIntersection(arr1, arr2));

Output

And the output in the console will be −

[
   [ 1, 2 ],
   [ 5, 5 ],
   [ 8, 10 ],
   [ 15, 23 ],
   [ 24, 24 ],
   [ 25, 25 ] 
]
Updated on: 2021-04-09T09:56:48+05:30

485 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements