Your cart is currently empty!
Three Pointers
Three Pointers is almost identical to “two pointers” except there is a third pointer (or “pincer”). This is useful for “three number sums”, or going with the ball factory example from the Two Pointer post, perhaps an item where three different balls are packaged together.
A use case that I find fascinating might be K Pincers/K Pointers where the number of pointers is determined on the fly. I would imagine something like that could be useful in the world of manufacturing where you might need to “tool up” a certain number of pincers/pointers to grab the correct combination of ingredients for some product.
function three_sum(arr, k) {
arr.sort((a, b) => a - b);
const triplets = [];
for (let thirdWheel = 0; thirdWheel < arr.length - 2; thirdWheel++) {
let leftIdx = thirdWheel + 1, rightIdx = arr.length - 1;
while (leftIdx < rightIdx) {
let currentSum = arr[thirdWheel] + arr[leftIdx] + arr[rightIdx];
if (currentSum === k) {
triplets.push([arr[thirdWheel], arr[leftIdx], arr[rightIdx]]);
leftIdx++;
rightIdx--;
} else if (currentSum < k) {
leftIdx++;
} else if (currentSum > k) {
rightIdx--;
}
}
}
return triplets;
}
console.log(three_sum([1,2,3,2,2,5,0,7,-1], 6))
Cast of Characters:
-Gordon Gekko
-Rabbi with Special K Cereal
-Expensive Accountant
-Lewis and Clark
-“The Third Wheel” … specific to this algorithm
-Wile E Coyote with a Three Pronged Pitch Fork