Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding intersection of arrays of intervals in JavaScript
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.
Problem Statement
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:
[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Algorithm Approach
The solution uses a two-pointer approach to traverse both arrays simultaneously. For each pair of intervals, we calculate the maximum of start points and minimum of end points to find potential intersection.
Solution
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
Output
[
[ 1, 2 ],
[ 5, 5 ],
[ 8, 10 ],
[ 15, 23 ],
[ 24, 24 ],
[ 25, 25 ]
]
How It Works
The algorithm works by:
- Two-pointer technique: Use pointers i and j to traverse arr1 and arr2 respectively
- Intersection calculation: For current intervals [a,b] and [c,d], intersection is [max(a,c), min(b,d)]
- Valid intersection: Only add to result if max(a,c) ? min(b,d)
- Pointer advancement: Move pointer of interval that ends first to avoid missing intersections
Time Complexity
Time complexity is O(m + n) where m and n are lengths of the input arrays, as we traverse each array once. Space complexity is O(k) where k is the number of intersecting intervals.
Conclusion
This two-pointer approach efficiently finds all intersections between sorted interval arrays in linear time. The key insight is advancing the pointer of the interval that ends first to ensure no intersections are missed.
