
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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 ] ]
- Related Questions & Answers
- Finding intersection of multiple arrays - JavaScript
- Finding the intersection of arrays of strings - JavaScript
- Finding intersection of arrays that contain repetitive entries in JavaScript
- Intersection of two arrays JavaScript
- Unique intersection of arrays in JavaScript
- Intersection of three sorted arrays in JavaScript
- Find Intersection of all Intervals in C++
- Finding the inclination of arrays in JavaScript
- Intersection of two arrays in C#
- Intersection of two arrays in Java
- Intersection of Two Arrays in C++
- Finding reversed index of elements in arrays - JavaScript
- Finding the continuity of two arrays in JavaScript
- Intersection of Two Arrays II in Python
- Intersection of Three Sorted Arrays in C++
Advertisements