Skip to main content

๐Ÿ‘ˆ๐Ÿ‘‰ Two Pointers

One-line summary: Use two indices that move toward each other (or in the same direction) to eliminate the O(nยฒ) nested loop โ€” achieving O(n) on sorted data.


Conceptโ€‹

Two pointers maintains two indices โ€” left and right โ€” and moves them strategically:

  • Opposite-direction (converging): both ends converge inward โ€” sorted array, palindrome, container problems.
  • Same-direction (fast/slow): both move forward, one faster โ€” remove duplicates, cycle detection, is-subsequence.

Prerequisite: sorted array (for opposite-direction), or logical ordering for same-direction.


Diagramโ€‹

Two Pointers Flow Two Pointers GIF

Sorted: [1, 2, 3, 4, 6] target=6
L R
Step 1: 1+6=7 > 6 โ†’ R--
Step 2: 1+4=5 < 6 โ†’ L++
Step 3: 2+4=6 โœ“

Time & Space Complexityโ€‹

VariantTimeSpace
Two Sum SortedO(n)O(1)
Remove duplicates / Move ZeroesO(n)O(1)
Merge sorted arraysO(m+n)O(1)
Is SubsequenceO(n)O(1)
Trapping Rain WaterO(n)O(1)

Common Patternsโ€‹

Pattern 1 โ€” Opposite Direction (Two Sum Sorted)โ€‹

function twoSumSorted(arr, target) {
let left = 0,
right = arr.length - 1;
while (left < right) {
const sum = arr[left] + arr[right];
if (sum === target) return [left, right];
if (sum < target) left++;
else right--;
}
return [];
}

Pattern 2 โ€” Same Direction (Move Zeroes)โ€‹

function moveZeroes(nums) {
let insertPos = 0;
for (let i = 0; i < nums.length; i++) if (nums[i] !== 0) nums[insertPos++] = nums[i];
while (insertPos < nums.length) nums[insertPos++] = 0;
}

Pattern 3 โ€” Fast/Slow (Is Subsequence)โ€‹

function isSubsequence(s, t) {
let i = 0,
j = 0;
while (i < s.length && j < t.length) {
if (s[i] === t[j]) i++;
j++;
}
return i === s.length;
}

Pattern 4 โ€” Fast/Slow (Cycle Detection in Linked List)โ€‹

function hasCycle(head) {
let slow = head,
fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}

When to Useโ€‹

  • Sorted arrays where you need to find pairs or triplets
  • Problems requiring partitioning or rearranging elements
  • Optimising brute-force O(nยฒ) solutions to O(n)
  • Palindrome checking in arrays/strings
  • Cycle detection in linked lists (fast/slow variant)

Pitfallsโ€‹

  • Forgetting to sort the array first (opposite-direction only works on sorted input)
  • Moving both pointers simultaneously instead of one at a time
  • Off-by-one: use left < right not left <= right for converging pointers

Practice Problemsโ€‹

ProblemDifficultySolution
LC 88 โ€” Merge Sorted ArrayEasyView Solution
LC 283 โ€” Move ZeroesEasyView Solution
LC 392 โ€” Is SubsequenceEasyView Solution
LC 977 โ€” Squares of a Sorted ArrayEasy
LC 844 โ€” Backspace String CompareEasy
LC 27 โ€” Remove ElementEasy
LC 125 โ€” Valid PalindromeEasy
LC 234 โ€” Palindrome Linked ListEasy
LC 344 โ€” Reverse StringEasy
LC 345 โ€” Reverse Vowels of a String LC 905 โ€” Sort Array By ParityEasy
LC 922 โ€” Sort Array By Parity IIEasy
LC 1089 โ€” Duplicate ZerosEasy
LC 1768 โ€” Merge Strings AlternatelyEasy
LC 1984 โ€” Minimum Difference Between Highest and Lowest of K ScoresEasy
CC โ€” String Rotation (ROTSTRNG)Easy
CC โ€” Palindrome Check (PALCHECK)Easy
CC โ€” Array Partition (ARRPART)Easy
CC โ€” Two Sum Sorted (TWOSUMSOR)Easy
CC โ€” Palindrome Check (PALCHECK)Easy
CC โ€” Array Partition (ARRPART)Easy
LC 15 โ€” 3SumMedium
LC 11 โ€” Container With Most WaterMedium
LC 16 โ€” 3Sum ClosestMedium
LC 18 โ€” 4SumMedium
LC 75 โ€” Sort ColorsMedium
LC 80 โ€” Remove Duplicates from Sorted Array IIMedium
LC 167 โ€” Two Sum II - Input Array Is SortedMedium
LC 209 โ€” Minimum Size Subarray SumMedium
LC 259 โ€” 3Sum SmallerMedium
LC 287 โ€” Find the Duplicate NumberMedium
LC 986 โ€” Interval List IntersectionsMedium
LC 1004 โ€” Max Consecutive Ones IIIMedium
LC 1040 โ€” Moving Stones Until Consecutive IIMedium
LC 1498 โ€” Number of Subsequences That Satisfy the Given Sum ConditionMedium
LC 1658 โ€” Minimum Operations to Reduce X to ZeroMedium
LC 1750 โ€” Minimum Length of String After Deleting Similar EndsMedium
CC โ€” Make Palindrome 2 (MAKEPAL2)Medium
CC โ€” Subarray with Given Sum (SUBSUM2)Medium
CC โ€” Container Water (CONTWATER)Medium
CC โ€” Two Pointer Technique (TWOPTR)Medium
CC โ€” Subarray with Given Sum (SUBSUM2)Medium
LC 42 โ€” Trapping Rain WaterHard
LC 76 โ€” Minimum Window SubstringHard
LC 923 โ€” 3Sum With MultiplicityHard
LC 1793 โ€” Maximum Score of a Good SubarrayHard
LC 1970 โ€” Last Day Where You Can Still CrossHard
LC 2040 โ€” Kth Smallest Product of Two Sorted ArraysHard
LC 2444 โ€” Count Subarrays With Fixed BoundsHard
CC โ€” Advanced Two Pointers (ADVTWOPTR)Hard
CC โ€” Rain Water Trapping (RAINWATER)Hard
LC 719 โ€” Find K-th Smallest Pair DistanceHard
LC 923 โ€” 3Sum With MultiplicityHard
CC โ€” Advanced Two Pointers (ADVTWOPTR)Hard

โ† Back to Home ยท ยฉ sparshjaswal