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
Pair whose sum exists in the array in JavaScript
In this article we will see how to find pairs of items in an array whose sum equals another element present in the same array. We'll use JavaScript to implement an efficient algorithm for this problem.
Understanding the Problem
The problem is to find pairs of numbers (a, b) in an array where a + b = c, and c is also present in the array. For example, in array [1, 2, 3, 4, 5], the pair (1, 2) has sum 3, which exists in the array.
Approach Using Hash Set
We'll use a Set data structure to efficiently check if a sum exists in the array. For each pair of elements, we calculate their sum and verify if it's present in our set.
Algorithm Steps
Step 1: Create a Set containing all array elements for O(1) lookup time.
Step 2: Use nested loops to generate all possible pairs from the array.
Step 3: For each pair, calculate the sum and check if it exists in our Set.
Step 4: Store valid pairs in the result array and return it.
Implementation
function findPairsWithSumExists(arr) {
// Create a set of all elements for fast lookup
const elementSet = new Set(arr);
const result = [];
// Check all possible pairs
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
const sum = arr[i] + arr[j];
// Check if sum exists in the array
if (elementSet.has(sum)) {
result.push([arr[i], arr[j], sum]);
}
}
}
return result;
}
// Test with example array
const arr = [1, 2, 3, 4, 5, 6];
const pairs = findPairsWithSumExists(arr);
console.log("Array:", arr);
console.log("Pairs with sum in array:", pairs);
Array: [ 1, 2, 3, 4, 5, 6 ] Pairs with sum in array: [ [ 1, 2, 3 ], [ 1, 3, 4 ], [ 1, 4, 5 ], [ 1, 5, 6 ], [ 2, 3, 5 ], [ 2, 4, 6 ] ]
Alternative Optimized Version
Here's a version that avoids duplicate pairs and provides cleaner output:
function findUniquePairsWithSum(arr) {
const elementSet = new Set(arr);
const result = [];
const seen = new Set();
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
const sum = arr[i] + arr[j];
const pairKey = `${Math.min(arr[i], arr[j])}-${Math.max(arr[i], arr[j])}`;
if (elementSet.has(sum) && !seen.has(pairKey)) {
result.push({
pair: [arr[i], arr[j]],
sum: sum
});
seen.add(pairKey);
}
}
}
return result;
}
const numbers = [1, 2, 3, 4, 5];
const uniquePairs = findUniquePairsWithSum(numbers);
uniquePairs.forEach(item => {
console.log(`${item.pair[0]} + ${item.pair[1]} = ${item.sum}`);
});
1 + 2 = 3 1 + 3 = 4 1 + 4 = 5 2 + 3 = 5
Complexity Analysis
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(n²) | Nested loops to check all pairs |
| Space | O(n) | Set storage for array elements |
Key Points
- Using a Set for element lookup provides O(1) search time
- The algorithm finds all pairs whose sum exists in the original array
- Avoid checking pairs twice by using proper loop indices
- Consider deduplication based on your specific requirements
Conclusion
This approach efficiently finds pairs whose sum exists in the array using a Set for fast lookups. While the time complexity is O(n²) due to pair generation, the Set optimization makes sum verification very fast.
