Counting pairs with range sum in a limit in JavaScript

In JavaScript, counting pairs with range sum within a limit involves finding all possible subarrays whose sum falls within a specified range. This is a common array processing problem that requires careful handling of cumulative sums.

Range Sum

Range sum rangeSum(i, j) is defined as the sum of the elements in an array between indices i and j (i ? j), inclusive.

Problem

We are required to write a JavaScript function that takes in an array of Integers, arr, as the first argument and two numbers, lower and upper as the second and third element.

Our function is supposed to return the number of range sums that lie between the range [lower, upper], (both inclusive).

For example, if the input to the function is:

const arr = [1, 4, 3];
const lower = 2;
const upper = 5;

Then the output should be:

3

Example

The code for this will be:

const arr = [1, 4, 3];
const upper = 5;
const lower = 2;

const countRangeSum = (arr = [], lower, upper) => {
    const sums = [0];
    let res = 0;
    let last = 0;
    
    let firstge = value => {
        let l = 0, r = sums.length, m;
        do {
            m = Math.floor((r + l) / 2);
            sums[m] = l + 2);
        while (r > 0 && sums[r - 1] >= value ) {
            r -= 1;
        }
        return r;
    };
    
    arr.forEach(num => {
        last += num;
        res += firstge(last - lower + 1) - firstge(last - upper);
        sums.splice(firstge(last), 0, last);
    });
    
    return res;
};

console.log(countRangeSum(arr, lower, upper));
3

How It Works

The algorithm uses prefix sums and binary search:

  • Maintains a sorted array of cumulative sums
  • For each element, calculates how many previous sums create valid ranges
  • Uses binary search to efficiently find count of sums in the target range

Simple Approach for Understanding

Here's a more straightforward approach to understand the concept:

const arr = [1, 4, 3];
const lower = 2;
const upper = 5;

const countRangeSumSimple = (arr, lower, upper) => {
    let count = 0;
    const n = arr.length;
    
    // Check all possible subarrays
    for (let i = 0; i = lower && sum 

Subarray [0,1]: sum = 5
Subarray [1,1]: sum = 4
Subarray [2,2]: sum = 3
Total count: 3

Conclusion

Counting range sums requires checking all subarrays against the given bounds. The optimized solution uses binary search for efficiency, while the simple approach helps understand the core concept.

Updated on: 2026-03-15T23:19:00+05:30

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements