Skip to content
DSA in JavaScript
← All patterns

Two Pointers

0/19 solved

What it is

Keep two positions in a sequence and move them toward each other (or the same way) based on what you see, instead of checking every pair.

Used for

Sorted arrays, pairs that hit a target, palindromes, removing duplicates in place.
left
right

target = 10

Step 1 of 6

Goal: find two numbers in this sorted list that add up to 10. Trying every pair is slow. Instead, put one marker at each end of the list.

You see

  • Sorted array or string
  • Pair or triplet with a target sum
  • Palindrome check
  • Remove duplicates in place

Learn it in

ArraysStringsPalindrome Check

Template

function twoSumSorted(a, target) {  let l = 0, r = a.length - 1;  while (l < r) {    const s = a[l] + a[r];    if (s === target) return [l, r];    s < target ? l++ : r--;  }  return null;}

Practice problems