Pair of (adjacent) elements of an array whose sum is lowest JavaScript

We are required to write a JavaScript function that takes in an array of numbers. The function should return a subarray of two adjacent elements from the original array whose sum is the least amongst all adjacent pairs of the array.

If the length of the array is less than 2, we should return boolean false.

Example Input

For example, if the input array is:

const arr = [41, 44, -12, 13, -23, 1, 5, -4, 2, 2];

Here, the sum of pair [-23, 1] is -22 which is the least for any two adjacent elements of the array, so the function should return [-23, 1].

Solution Using Array.reduce()

const arr = [41, 44, -12, 13, -23, 1, 5, -4, 2, 2];

const leastSum = arr => {
    if(arr.length  {
        let { smallest, startIndex } = acc;
        const next = arr[ind + 1];
        
        if(!next){
            return acc;
        }
        
        const sum = val + next;
        if(sum 

[-23, 1]

Alternative Solution Using Simple Loop

Here's a more straightforward approach using a for loop:

const findLowestSum = arr => {
    if(arr.length 

[-23, 1]

How It Works

The algorithm iterates through the array, calculating the sum of each pair of adjacent elements. It keeps track of the minimum sum found and the starting index of that pair. Finally, it returns the pair with the lowest sum.

Edge Cases

// Array with less than 2 elements
console.log(leastSum([5])); // false
console.log(leastSum([]));  // false

// Array with only 2 elements
console.log(leastSum([10, -5])); // [10, -5]
false
false
[10, -5]

Conclusion

Both approaches effectively find the adjacent pair with the minimum sum. The loop-based solution is more readable, while the reduce method demonstrates functional programming techniques in JavaScript.

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

531 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements