Opposite Direction Pointers
Opposite direction pointers start at the two ends of an array or string and move toward each other. They are ideal when the solution depends on comparing or combining values at both ends.
When to Use
- Sorted array: Find a pair with a given sum (or two values satisfying a condition).
- Palindrome check on a string or array.
- Partition / in-place operations (e.g. move zeros, Dutch national flag) where you swap or assign based on values at both ends.
Two Sum in Sorted Array
Given a sorted array and a target, find two indices whose values sum to the target.
- Put
leftat 0 andrightatn - 1. - If
arr[left] + arr[right] == target, return. - If sum is too small, increment
left; if too large, decrementright.
Javapublic int[] twoSum(int[] numbers, int target) { int left = 0, right = numbers.length - 1; while (left < right) { int sum = numbers[left] + numbers[right]; if (sum == target) return new int[]{left + 1, right + 1}; if (sum < target) left++; else right--; } return new int[]{}; }
Time O(n), space O(1).
Valid Palindrome
Check if a string reads the same forward and backward (ignoring non-alphanumeric and case).
- Use
leftandrightat the two ends; move them inward, skipping non-alphanumeric characters; compare at each step.
Javapublic boolean isPalindrome(String s) { int left = 0, right = s.length() - 1; while (left < right) { while (left < right && !Character.isLetterOrDigit(s.charAt(left))) left++; while (left < right && !Character.isLetterOrDigit(s.charAt(right))) right--; if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) return false; left++; right--; } return true; }
Summary
Opposite-direction pointers give O(n) time and O(1) space when the array or string is (or can be) processed from both ends. Use them for pair sum in a sorted array, palindromes, and many in-place partition problems.