Skip to content

Instantly share code, notes, and snippets.

@remi-bruguier
Created May 25, 2020 20:32
Show Gist options
  • Save remi-bruguier/29a5ce009a33747b3ba74d2c92884b3b to your computer and use it in GitHub Desktop.
Save remi-bruguier/29a5ce009a33747b3ba74d2c92884b3b to your computer and use it in GitHub Desktop.
Given a list of numbers, find if there exists a pythagorean triplet in that list. A pythagorean triplet is 3 variables a, b, c where a² + b² = c²
const findPythagoreanTriplets = (arr:number[]):boolean => {
if(arr.length<3) return false;
const sorted = arr
.map(v => v*v)
.sort((a,b) => a-b);
let [l,r,i] = [0, sorted.length -2, sorted.length -1];
while(i>=2){
if(sorted[l] + sorted[r] == sorted[i]){
return true;
}
if(l==r){
l = 0;
r--;
i--;
}
l++;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment