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