Skip to content

Instantly share code, notes, and snippets.

@Aldizh
Last active September 15, 2023 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aldizh/5da1877cef5e5db2b6e7c4169e3796a1 to your computer and use it in GitHub Desktop.
Save Aldizh/5da1877cef5e5db2b6e7c4169e3796a1 to your computer and use it in GitHub Desktop.
// 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