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
Adjacent elements of array whose sum is closest to 0 - JavaScript
We are required to write a JavaScript function that takes in an array of numbers and returns a subarray of two adjacent elements from the original array whose sum is closest to 0.
If the length of the array is less than 2, we should return the whole array.
Problem Statement
For example: If the input array is ?
const arr = [4, 4, 12, 3, 3, 1, 5, -4, 2, 2];
Here, the sum of adjacent pair [5, -4] is 1 which is closest to 0 for any two adjacent elements of the array, so we should return [5, -4].
Approach
We'll iterate through the array and check each pair of adjacent elements. For each pair, we calculate the absolute difference between their sum and 0, keeping track of the pair with the smallest difference.
Example
const arr = [4, 4, 12, 3, 3, 1, 5, -4, 2, 2];
const closestElements = (arr, target = 0) => {
if(arr.length <= 2){
return arr;
}
const result = arr.reduce((acc, val, ind) => {
let { closest, startIndex } = acc;
const next = arr[ind + 1];
if(!next){
return acc;
}
const diff = Math.abs(target - (val + next));
if(diff < closest){
startIndex = ind;
closest = diff;
}
return { startIndex, closest };
}, {
closest: Infinity,
startIndex: -1
});
const { startIndex: s } = result;
return [arr[s], arr[s + 1]];
};
console.log(closestElements(arr, 0));
console.log("Sum:", closestElements(arr, 0)[0] + closestElements(arr, 0)[1]);
[5, -4] Sum: 1
How It Works
The function uses the reduce method to iterate through the array:
- For each element, it checks the next adjacent element
- Calculates the absolute difference between the sum of the pair and the target (0)
- Keeps track of the pair with the smallest difference
- Returns the optimal pair as an array
Edge Case Example
// Array with less than 2 elements const smallArr = [5]; console.log(closestElements(smallArr, 0)); // Array with exactly 2 elements const twoElements = [3, -2]; console.log(closestElements(twoElements, 0));
[5] [3, -2]
Conclusion
This algorithm efficiently finds adjacent elements with sum closest to 0 using a single pass through the array. The time complexity is O(n) and space complexity is O(1).
