
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding Three Elements with Required Sum in an Array in JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number as the second argument. The function should then pick three such numbers from the array, (if they exist) whose sum is equal to the number specified by the second argument.
The function should finally return an array of arrays of all such triplets if they exist, an empty array otherwise.
For example −
If the input array and the number is −
const arr = [2, 5, 7, 8, 9, 11, 1, 6]; const sum = 22;
Then the output should be −
const output = [ [ 2, 9, 11 ], [ 5, 6, 11 ], [ 5, 8, 9 ], [ 6, 7, 9 ] ];
Example
The code for this will be −
const arr = [2, 5, 7, 8, 9, 11, 1, 6]; const sum = 22; const threeSum = (arr = [], sum) => { arr.sort((a,b) => a - b); const res = []; for(let i=0; i < arr.length - 2; i++){ if(arr[i] != arr[i-1]){ let left = i + 1; let right = arr.length - 1; while (left < right){ const curr = arr[i] + arr[left] + arr[right]; if (curr === sum){ res.push([arr[i], arr[left], arr[right]]); while(arr[left] == arr[left + 1]) left ++ while(arr[right] == arr[right - 1]) right -- // making sure our solution set does not contain duplicate res left ++; right --; } else if(curr < sum) { left ++ } else if(curr > sum){ right -- }; }; }; }; return res }; console.log(threeSum(arr, sum));
Output
And the output in the console will be −
[ [ 2, 9, 11 ], [ 5, 6, 11 ], [ 5, 8, 9 ], [ 6, 7, 9 ] ]
Advertisements