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
Algorithm to sum ranges that lie within another separate range in JavaScript
We have two sets of ranges; one is a single range of any length (R1) and the other is a set of ranges (R2) some or parts of which may or may not lie within the single range (R1).
We need to calculate the sum of the ranges in (R2) - whole or partial - that lie within the single range (R1).
Problem Breakdown
For each range in R2, we calculate the overlapping portion with R1 and sum all overlaps:
const R1 = [20,40]; const R2 = [[14,22],[24,27],[31,35],[38,56]]; // Overlap calculations: // [14,22] with [20,40] = [20,22] = 2 // [24,27] with [20,40] = [24,27] = 3 // [31,35] with [20,40] = [31,35] = 4 // [38,56] with [20,40] = [38,40] = 2
Expected result: 2 + 3 + 4 + 2 = 11
Algorithm
The algorithm finds the intersection of each range in R2 with R1 using:
-
Left boundary:
Math.max(rangeStart, targetStart) -
Right boundary:
Math.min(rangeEnd, targetEnd) -
Overlap length:
Math.max(0, rightBoundary - leftBoundary)
Implementation
const R1 = [20,40];
const R2 = [[14,22],[24,27],[31,35],[38,56]];
const R3 = [120,356];
const R4 = [[234,567]];
function sumRanges(range, values) {
const [start, end] = range;
const res = values.reduce((acc, val) => {
const [left, right] = val;
const ex1 = Math.min(right, end);
const ex2 = Math.max(left, start);
const diff = ex1 - ex2;
return acc + Math.max(0, diff);
}, 0);
return res;
}
console.log(sumRanges(R1, R2));
console.log(sumRanges(R3, R4));
11 122
Step-by-Step Explanation
Let's trace through the first example:
function sumRangesDetailed(range, values) {
const [start, end] = range;
console.log(`Target range: [${start}, ${end}]`);
let total = 0;
values.forEach((val, index) => {
const [left, right] = val;
const rightBoundary = Math.min(right, end);
const leftBoundary = Math.max(left, start);
const overlap = Math.max(0, rightBoundary - leftBoundary);
console.log(`Range ${index + 1}: [${left}, ${right}] ? overlap: ${overlap}`);
total += overlap;
});
return total;
}
sumRangesDetailed([20,40], [[14,22],[24,27],[31,35],[38,56]]);
Target range: [20, 40] Range 1: [14, 22] ? overlap: 2 Range 2: [24, 27] ? overlap: 3 Range 3: [31, 35] ? overlap: 4 Range 4: [38, 56] ? overlap: 2 11
Conclusion
This algorithm efficiently calculates range overlaps using min/max operations to find intersection boundaries. It handles partial overlaps and non-overlapping ranges correctly by using Math.max(0, diff) to ensure non-negative results.
