Last active
September 15, 2023 17:37
-
-
Save Aldizh/5da1877cef5e5db2b6e7c4169e3796a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Function to find triplets with zero sum. | |
/** | |
* @param {number[]} arr | |
* @param {number} n | |
* @returns {boolean} | |
*/ | |
function findTriplets(arr, n) | |
{ | |
// your code here | |
// naive approach: 3 nested loops and compare intersecting sum = 0; | |
// more intelligent approach: reduce to a pair sum problem | |
// This involves traversing through the array. | |
// For every element arr[i], find a pair with sum “-arr[i]”. | |
var found = false; | |
var combos = [] | |
for (var i = 0; i < n - 1; i++) { | |
var elements = new Set() // add current element to compare against pair combos | |
// iterate through comninations of sum pairs | |
// if the current elemen matches the negative of the pair we are done | |
for (var j = i + 1; j < n; j++) { | |
var x = -(arr[i] + arr[j]); | |
if (elements.has(x)) { found = true; combos.push([x, arr[i], arr[j]])} | |
else elements.add(arr[j]) | |
} | |
} | |
// console.log('combos', combos) | |
return found === false ? 0 : 1 | |
} | |
findTriplets([0, -1, 1, 2, -3, 1, 9, 7, 6], 9) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment