Two Pointers Pattern
šÆ Explain Like I'm 5...
Imagine you have a row of 10 toy blocks numbered 1 to 10. You want to find two blocks that add up to 11!
š§ Kid's Way (Slow): Pick block 1, then check it with ALL other blocks (1+2, 1+3, 1+4...). Then pick block 2 and check with all others (2+3, 2+4...). This takes FOREVER! š“
š§ Smart Way (Two Pointers): Put your LEFT hand š on block 1 and RIGHT hand š on block 10.
- ⢠Add them: 1 + 10 = 11 ā Found it! š
- ⢠If sum is too small, move LEFT hand right ā
- ⢠If sum is too big, move RIGHT hand left ā
š Why is it faster? Instead of checking EVERY pair (45 checks!), we only move our hands closer until we find the answer. Much smarter! It's like having two helpers working together instead of one person doing all the work alone.
šØ See It In Action!
Below you'll find interactive animations for each example. Use the controls to play, pause, and step through each algorithm!
When Should You Use This Pattern?
- āThe array or string is sorted (or you can sort it)
- āYou need to find a pair of numbers
- āYou want to check if something is a palindrome
- āYou need to remove duplicates
š Example 1: Find Two Numbers That Add Up to Target
Let's say you have a sorted array: [1, 2, 3, 4, 6] and you want to find two numbers that add up to 6.
š¬ Two Sum - Finding pairs that add to target
1 + 6 = 7 (too big, move right pointer left)
Step-by-Step Thinking:
- Put one pointer at the start (left = 0), one at the end (right = 4)
- Add the numbers at both pointers: 1 + 6 = 7 (too big!)
- Move the right pointer left: 1 + 4 = 5 (too small!)
- Move the left pointer right: 2 + 4 = 6 (Perfect! ā)
public class TwoSum { // Function to find two numbers that add up to target public static int[] findPair(int[] arr, int target) { // Start with two pointers int left = 0; // š starts at beginning int right = arr.length - 1; // š starts at end // Keep going until pointers meet while (left < right) { int sum = arr[left] + arr[right]; if (sum == target) { // Found it! Return the pair return new int[]{arr[left], arr[right]}; } else if (sum < target) { // Sum too small, move left pointer right left++; } else { // Sum too big, move right pointer left right--; } } // No pair found return new int[]{-1, -1}; } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 6}; int target = 6; int[] result = findPair(arr, target); System.out.println("Pair: " + result[0] + " + " + result[1]); // Output: Pair: 2 + 4 }}š Example 2: Check if String is a Palindrome
A palindrome reads the same forwards and backwards, like "racecar" or "mom".
š¬ Palindrome Check - Comparing from both ends
Compare 'r' and 'r' - match! Continue...
public class Palindrome { public static boolean isPalindrome(String str) { // Remove spaces and convert to lowercase str = str.toLowerCase().replaceAll(" ", ""); int left = 0; // š starts at beginning int right = str.length() - 1; // š starts at end while (left < right) { // Compare characters at both pointers if (str.charAt(left) != str.charAt(right)) { return false; // Not matching = not palindrome } // Move both pointers towards center left++; right--; } return true; // All characters matched! } public static void main(String[] args) { System.out.println(isPalindrome("racecar")); // true System.out.println(isPalindrome("hello")); // false System.out.println(isPalindrome("A man a plan a canal Panama")); // true }}š Example 3: Remove Duplicates from Sorted Array
Given [1, 1, 2, 2, 3, 4, 4], remove duplicates to get [1, 2, 3, 4].
š¬ Remove Duplicates - Using slow and fast pointers
1 == 1 (duplicate, only fast moves)
public class RemoveDuplicates { public static int removeDuplicates(int[] arr) { if (arr.length == 0) return 0; int slow = 0; // Points to last unique element // Fast pointer explores the array for (int fast = 1; fast < arr.length; fast++) { // Found a new unique element? if (arr[fast] != arr[slow]) { slow++; // Move slow pointer arr[slow] = arr[fast]; // Place unique element } } return slow + 1; // Number of unique elements } public static void main(String[] args) { int[] arr = {1, 1, 2, 2, 3, 4, 4}; int uniqueCount = removeDuplicates(arr); System.out.print("Unique elements: "); for (int i = 0; i < uniqueCount; i++) { System.out.print(arr[i] + " "); } // Output: Unique elements: 1 2 3 4 }}š Key Points to Remember
- 1ļøā£Two pointers help you avoid nested loops (faster than O(n²)!)
- 2ļøā£Usually works best with sorted arrays
- 3ļøā£Time Complexity: O(n) - you only go through the array once!
- 4ļøā£Space Complexity: O(1) - you only use two variables!
šŖ Practice Problems
- ⢠Container With Most Water
- ⢠3Sum Problem
- ⢠Sort Colors (Dutch National Flag)
- ⢠Trapping Rain Water
- ⢠Remove Element