Skip to the page

Linear patterns · core

Two pointers in JavaScript

Two pointers walk a sorted array or a string from both ends (or at two speeds), so a pair search drops from O(n²) to O(n) with O(1) extra space. In JavaScript, sort numbers with a comparator first, and turn a string into an array before any in-place change.

The notes

What you must know

  • Opposite ends on sorted input: sum too small → move left up; too big → move right down. Each step removes one candidate, so it is O(n).
  • Same direction (read/write): one pointer reads, one writes the next kept value — remove duplicates, move zeros, compact arrays in place.
  • Fast/slow pointers: find the middle, detect cycles (Floyd), find the k-th from the end.
  • 3Sum = sort + fix i + two pointers on the rest: O(n²). Skip duplicates at i, and after a match skip equal values at both pointers.
  • Palindrome check: test each character with /[a-z0-9]/i, skip the others, and compare s[l].toLowerCase() with s[r].toLowerCase(). Building a cleaned copy with replace() and split('').reverse().join('') works but uses O(n) extra memory.
  • If the input is not sorted, sorting first costs O(n log n) and loses original indices; a Map may be better when indices are needed.
  • Sort numbers with a comparator: nums.sort((a, b) => a - b). The default sort compares strings, so [10, 9, 1].sort() gives [1, 10, 9] and the pointers move the wrong way.
  • Swap with destructuring: [a[l], a[r]] = [a[r], a[l]]. A string has no in-place swap: convert it with [...s] first, then join('').

The red pen

Common traps: mistake → fix

  • Mistake: Two pointers work on any array

    Fix: the move rule needs sorted data (or a palindrome-like symmetry).

  • Mistake: 3Sum duplicates can be removed with a Set of strings at the end

    Fix: it works but hides the O(n²) skip logic interviewers expect.

  • Mistake: After a match you can move only one pointer

    Fix: move both, then skip equal values.

  • Mistake: nums.sort() sorts numbers

    Fix: without (a, b) => a - b it sorts them as strings.

Easy to hard

Questions interviewers ask, easy to hard

  1. Find a pair with a target sum in a sorted array, O(1) extra space.
  2. Remove duplicates from a sorted array in place.
  3. 3Sum with no duplicate triplets. Why can't hashing beat O(n²) here?
  4. Valid palindrome ignoring punctuation and case.

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview