
Many array problems look like they need nested loops.
That means O(n²) time.
But with one simple idea — Two Pointers —
you can often reduce it to O(n).
What is Two Pointer Technique?
Instead of using one loop,
you use two indices (pointers):
- From opposite ends
- Or moving in the same direction
Helps reduce unnecessary work
Example 1: Two Sum (Sorted Array)
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};
}
Idea:
- If sum is small → move left
- If sum is large → move right
Example 2: Remove Duplicates
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;
}
Idea:
- One pointer reads
- One pointer writes
Example 3: Container With Most Water
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;
}
Idea:
- Move pointer with smaller height
The Real Insight
Two pointers eliminate unnecessary comparisons
Instead of checking all pairs,
you move intelligently.
Key Insights
- Works best on sorted arrays
- Can be used for in-place operations
- Reduces O(n²) → O(n)
For More: https://www.quipoin.com/tutorial/data-structure-with-java/two-pointer-technique
Top comments (0)