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
Selected Reading
Finding closest pair sum of numbers to a given number in JavaScript
We need to write a JavaScript function that takes an array of numbers and a target number, then returns the pair of numbers from the array whose sum is closest to the target.
The function should find two different numbers from the original array that, when added together, produce a sum nearest to the specified target value.
Basic Approach Using Nested Loops
Here's a straightforward solution using nested loops to check all possible pairs:
const arr = [1, 2, 3, 4, 5, 6, 7];
const num = 14;
const closestPair = (arr, target) => {
let bestPair = [0, 0];
let closestDiff = Infinity;
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
let sum = arr[i] + arr[j];
let diff = Math.abs(target - sum);
if (diff < closestDiff) {
closestDiff = diff;
bestPair = [arr[i], arr[j]];
}
}
}
return bestPair;
};
console.log(closestPair(arr, num));
console.log("Target:", num);
console.log("Sum of pair:", closestPair(arr, num)[0] + closestPair(arr, num)[1]);
[6, 7] Target: 14 Sum of pair: 13
Optimized Two-Pointer Approach
For sorted arrays, we can use a more efficient two-pointer technique:
const closestPairOptimized = (arr, target) => {
// Sort array first
const sorted = [...arr].sort((a, b) => a - b);
let left = 0;
let right = sorted.length - 1;
let bestPair = [sorted[0], sorted[1]];
let closestDiff = Math.abs(target - (sorted[0] + sorted[1]));
while (left < right) {
const sum = sorted[left] + sorted[right];
const diff = Math.abs(target - sum);
if (diff < closestDiff) {
closestDiff = diff;
bestPair = [sorted[left], sorted[right]];
}
if (sum < target) {
left++;
} else {
right--;
}
}
return bestPair;
};
const testArray = [10, 22, 28, 29, 30, 40];
const targetSum = 54;
console.log("Array:", testArray);
console.log("Target:", targetSum);
console.log("Closest pair:", closestPairOptimized(testArray, targetSum));
Array: [10, 22, 28, 29, 30, 40] Target: 54 Closest pair: [22, 30]
Handling Edge Cases
const robustClosestPair = (arr, target) => {
if (arr.length < 2) {
return null; // Need at least 2 elements
}
let bestPair = [arr[0], arr[1]];
let closestDiff = Math.abs(target - (arr[0] + arr[1]));
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
const sum = arr[i] + arr[j];
const diff = Math.abs(target - sum);
if (diff < closestDiff) {
closestDiff = diff;
bestPair = [arr[i], arr[j]];
}
}
}
return bestPair;
};
// Test with different cases
console.log("Empty array:", robustClosestPair([], 10));
console.log("Single element:", robustClosestPair([5], 10));
console.log("Normal case:", robustClosestPair([1, 3, 5, 8], 9));
Empty array: null Single element: null Normal case: [1, 8]
Performance Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Nested Loops | O(n²) | O(1) | Small arrays, unsorted data |
| Two Pointers | O(n log n) | O(n) | Large arrays, can modify order |
Conclusion
The nested loop approach works for any array but has O(n²) complexity. For better performance with larger datasets, use the two-pointer method after sorting the array first.
Advertisements
