Two Pointers

The code below is basically the same as the initial example used in the glossary, but doesn’t use reduce. For simpler memorization of the pattern, this example is better.

As for the “What” and “Why” of Two Pointers, a frequent example would be some target value, and you need to iterate through some list/array to find the two composite values that add up to the target sum.

In a real world analogy, imagine you own a rubber ball factory. The balls are manufactured with random colors, and you have two robot pincers that move about (over some row or aisle of balls) and need to grab two balls of differing color for packaging. Each pointer might represent a pincer.

AGAIN, the example below is similar to the example from the glossary, but perhaps easier to memorize because it doesn’t make use reduce.

function pair_with_target_k(arr, k) {
  arr.sort((a, b) => a - b)

  let leftIdx = 0,
    rightIdx = arr.length - 1;

  while (leftIdx < rightIdx) {
    let currentSum = arr[leftIdx] + arr[rightIdx];
    if (currentSum === k) {
      return true;
    } else if (k > currentSum) {
      leftIdx += 1; 
    } else if (k < currentSum) {
      rightIdx -= 1; 
    }
  }
  return false;
}

console.log(pair_with_target_k([1, 9, -3, 8], 5));
console.log(pair_with_target_k([13, 15, 9, -2, 8], 11));

Cast of Characters:
-Expensive Accountant
-Lewis and Clark
-Rabbi with a Cigar Cutter
-Wile E Coyote with a Three Pronged Pitchfork
(rearrange into a story that fit the above)

The follow example is essentially the same type of problem, except instead of returning the values that add up to the target, it returns the array indexes from the original unsorted array.

nums = [1,2,7,3,4,16,8]

function twoNumSum(arr, target) {
  let targetSumsAndIndexes = {}

  for (let index = 0; index < arr.length; index++) {
    
    const pointerValue = arr[index]
    const correspondingArrayIndex = targetSumsAndIndexes[pointerValue]
    
    if (correspondingArrayIndex >= 0) {
      return [correspondingArrayIndex, index]
    } else {
      const numberToFind = target - arr[index]
      targetSumsAndIndexes[numberToFind] = index
    }
  } 
  return null

}

console.log(twoNumSum(nums, 15))

Glossary of Code Personified

Return to the Pattern Directory

Discover more from Comedy Tragedy Epic

Subscribe now to keep reading and get access to the full archive.

Continue reading