Two Pointer Technique
When you have two pointers moving through an array, often from opposite ends or at different speeds, you can solve problems efficiently in O(n) time. Two-pointer technique is especially powerful for sorted arrays and palindrome checks.
Example 1: Two Sum (sorted array)
Find pair that sums to target.
public static int[] twoSumSorted(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) return new int[]{left, right};
else if (sum < target) left++;
else right--;
}
return new int[]{-1, -1};
}
Example 2: Remove duplicates from sorted array
Two pointers: one for reading, one for writing.
public static int removeDuplicates(int[] arr) {
if (arr.length == 0) return 0;
int writeIndex = 1;
for (int readIndex = 1; readIndex < arr.length; readIndex++) {
if (arr[readIndex] != arr[readIndex - 1]) {
arr[writeIndex++] = arr[readIndex];
}
}
return writeIndex;
}
Example 3: Container with most water
Classic problem: find two lines that form a container with max area.
public static int maxArea(int[] height) {
int left = 0, right = height.length - 1, max = 0;
while (left < right) {
max = Math.max(max, (right - left) * Math.min(height[left], height[right]));
if (height[left] < height[right]) left++;
else right--;
}
return max;
}
Two Minute Drill
- Two-pointer technique uses two indices moving towards each other or in same direction.
- Works well on sorted arrays (two sum, three sum).
- Used for in-place modifications (remove duplicates, partition).
- Time complexity usually O(n).
- Common in interview problems.
Need more clarification?
Drop us an email at career@quipoinfotech.com
