Sum is to be calculated for the numbers in between the array's max and min value JavaScript

We need to write a function called sumBetween() that takes an array of two elements and returns the sum of all integers between those values, including both endpoints.

For example:

[4, 7] = 4+5+6+7 = 22
[10, 6] = 10+9+8+7+6 = 40

Understanding the Problem

The function should work regardless of which number is larger. Whether we pass [4, 7] or [7, 4], we need to sum all integers from 4 to 7 inclusive.

Solution Using Mathematical Formula

We can use the mathematical formula for sum of consecutive integers: sum from 1 to n is n*(n+1)/2. To find the sum between two numbers, we calculate the difference between two cumulative sums.

const arr = [10, 60];

const sumUpto = (n) => (n*(n+1))/2;

const sumBetween = (array) => {
    if(array.length !== 2){
        return -1;
    }
    const [a, b] = array;
    return sumUpto(Math.max(a, b)) - sumUpto(Math.min(a, b)) + Math.min(a, b);
};

console.log(sumBetween(arr));
console.log(sumBetween([4, 9]));
console.log(sumBetween([7, 4])); // Same as [4, 7]
1785
39
22

Alternative Approach: Simple Loop

For better readability, we can use a simple loop approach:

const sumBetweenLoop = (array) => {
    if(array.length !== 2) return -1;
    
    const [a, b] = array;
    const min = Math.min(a, b);
    const max = Math.max(a, b);
    
    let sum = 0;
    for(let i = min; i <= max; i++) {
        sum += i;
    }
    return sum;
};

console.log(sumBetweenLoop([4, 7]));   // 4+5+6+7
console.log(sumBetweenLoop([10, 6]));  // 6+7+8+9+10
22
40

How the Mathematical Approach Works

The formula sumUpto(max) - sumUpto(min-1) calculates the sum between min and max. Since sumUpto(min-1) is equivalent to sumUpto(min) - min, we get: sumUpto(max) - sumUpto(min) + min.

Comparison

Approach Time Complexity Readability
Mathematical Formula O(1) Less intuitive
Simple Loop O(n) More intuitive

Conclusion

The mathematical approach is more efficient for large ranges, while the loop approach is easier to understand. Both methods correctly handle arrays where the first element is larger than the second.

Updated on: 2026-03-15T23:18:59+05:30

207 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements