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
How to find a group of three elements in an array whose sum equals some target sum JavaScript
We need to write a function that finds three elements in an array whose sum equals a target value. The function should return the indices of these three elements, or -1 if no such triplet exists.
Approach
We'll use a two-step approach:
- Create a
twoSum()helper function that finds two numbers adding up to a target sum - Iterate through each element and use
twoSum()to find the remaining two elements
This approach has O(N²) time complexity, where N is the array length.
How It Works
The twoSum() function uses a hash map to store array values and their indices. For each element, it checks if the complement (target - current element) exists in the map.
The threeSum() function iterates through each element as a potential first element, then calls twoSum() to find two elements that sum to (target - first element).
Example
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const twoSum = (arr, sum) => {
const map = {};
for(let i = 0; i < arr.length; i++){
if(map[sum - arr[i]] !== undefined){
return [map[sum - arr[i]], i];
}
map[arr[i]] = i;
}
return -1;
};
const threeSum = (arr, sum) => {
for(let i = 0; i < arr.length; i++){
const indices = twoSum(arr, sum - arr[i]);
if(indices !== -1 && !indices.includes(i)){
return [i, ...indices];
}
}
return -1;
};
console.log(threeSum(arr, 9)); // Find three elements that sum to 9
console.log(threeSum(arr, 8)); // Find three elements that sum to 8
console.log(threeSum(arr, 13)); // Find three elements that sum to 13
console.log(threeSum(arr, 23)); // Find three elements that sum to 23
[ 0, 2, 4 ] [ 0, 2, 3 ] [ 0, 4, 6 ] -1
Step-by-Step Breakdown
For threeSum(arr, 9):
- i=0: arr[0]=1, need twoSum for target 8. Found at indices [2,4] (values 3,5). Result: [0,2,4]
- Elements: arr[0]=1, arr[2]=3, arr[4]=5. Sum: 1+3+5=9 ?
Key Points
- The algorithm avoids using the same index twice by checking
!indices.includes(i) - Returns -1 when no valid triplet exists
- Uses hash map lookup for efficient two-sum computation
- Time complexity: O(N²), Space complexity: O(N)
Conclusion
This three-sum algorithm efficiently finds triplets by combining hash map lookups with iteration. It's a practical solution for finding three elements that sum to a target value in quadratic time.
