The two pointers idea
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Whenever a brute-force solution uses two nested loops (for i and for j) to compare pairs or compact elements in an array, ask whether i and j really need to reset on every iteration. The two pointers pattern coordinates two index variables so each pointer moves only in one direction, collapsing O(n²) work into a single O(n) pass.
One loop instead of two
Two pointers is a technique that moves two indexes through an array, often from both ends or at different speeds, to solve a problem in O(n) instead of O(n^2).
In Java, a pointer in an array or string problem simply means an int index variable such as left, right, read, or write.
int[] nums = {1, 3, 4, 6, 9};int target = 13;int left = 0, right = nums.length - 1; // two int "pointers"while (left < right) { int sum = nums[left] + nums[right]; if (sum == target) break; // 4 + 9 after only 3 steps if (sum < target) left++; // neither pointer ever moves back else right--;}In a naive nested loop, for each of the n positions of i, the inner index j scans up to n positions from scratch, performing roughly (n(n-1))/2 = O(n²) comparisons.
The two-pointers insight is to use information from the current comparison to eliminate an entire row or column of pairs at once. Instead of resetting j back to i + 1, each step advances at least one of the two pointers by 1 toward its goal. Because each pointer can move at most n times before the loop ends, the total number of iterations is at most 2n = O(n) time with O(1) auxiliary space.
- Brute force:
jresets for everyi, costing O(n²) steps. - Two pointers: neither pointer ever backs up, costing at most 2n = O(n) steps.
- Space: only two
intindex variables are needed (O(1) extra memory).
Pointers from both ends versus the same direction
Most two-pointer algorithms use one of three setups: pointers from both ends, pointers moving the same way, or one pointer in each of two arrays.
- Ask: am I comparing opposite ends / pairs in a sorted order? Choose converging pointers (
left = 0, right = n - 1). - Ask: am I filtering or compacting an array in place while keeping order? Choose same-direction pointers (
write = 0, read = 0..n-1). - Ask: am I combining two separate sorted inputs? Choose one pointer per array (
i = 0, j = 0).
Example 1 · Brute force: square every value, then sort (O(n log n) time, O(n) space)
import java.util.Arrays;
public class SortedSquaresBrute { public static int[] sortedSquares(int[] nums) { int[] result = new int[nums.length]; for (int i = 0; i < nums.length; i++) { result[i] = nums[i] * nums[i]; } Arrays.sort(result); return result; }
public static void main(String[] args) { int[] nums = {-7, -3, 2, 3, 11}; System.out.println("Input: " + Arrays.toString(nums)); System.out.println("Squares: " + Arrays.toString(sortedSquares(nums))); }}Input: [-7, -3, 2, 3, 11] Squares: [4, 9, 9, 49, 121]
What this code does
- Every value is squared, then
Arrays.sortputs the squares in order. It is correct and short. - The cost is the sort: O(n log n) time. It ignores that the input was already sorted, which means the biggest squares can only be at the two ends.
Example 2 · Optimal: converging pointers fill the result from the back (O(n) time, O(n) space)
import java.util.Arrays;
public class SortedSquaresDemo { // Input is sorted: [-7, -3, 2, 3, 11] // Largest squares sit at the two extreme ends! public static int[] sortedSquares(int[] nums) { int n = nums.length; int[] result = new int[n]; int left = 0; int right = n - 1; int pos = n - 1; // Fill result from largest to smallest
while (left <= right) { int leftSq = nums[left] * nums[left]; int rightSq = nums[right] * nums[right]; if (leftSq > rightSq) { result[pos--] = leftSq; left++; } else { result[pos--] = rightSq; right--; } } return result; }
public static void main(String[] args) { int[] nums = {-7, -3, 2, 3, 11}; System.out.println("Input: " + Arrays.toString(nums)); System.out.println("Squares: " + Arrays.toString(sortedSquares(nums))); }}Input: [-7, -3, 2, 3, 11] Squares: [4, 9, 9, 49, 121]
What this code does
- Squaring each element and calling
Arrays.sortwould take O(n log n) time. - Because negative numbers have their largest squares on the far left and positive numbers have their largest squares on the far right, converging pointers
leftandrightfillresultfrom back to front in one O(n) pass. - Why it is faster: the largest square is always at one of the two ends, so one comparison fixes one final position. n comparisons replace a full sort.
Example 3 · Same-direction pointers: compacting non-negative numbers in place
import java.util.Arrays;
public class SameDirectionDemo { // Keep only non-negative numbers at the front in their original order // Returns the new logical length public static int keepNonNegative(int[] nums) { int write = 0; for (int read = 0; read < nums.length; read++) { if (nums[read] >= 0) { nums[write] = nums[read]; write++; } } return write; }
public static void main(String[] args) { int[] data = {4, -1, 0, -9, 7, 2, -3}; int len = keepNonNegative(data); System.out.println("Kept count: " + len); System.out.println("Valid prefix: " + Arrays.toString(Arrays.copyOf(data, len))); }}Kept count: 4 Valid prefix: [4, 0, 7, 2]
What this code does
- The input is NOT sorted, and we must preserve the original left-to-right order
[4, 0, 7, 2]. readvisits every element once;writemarks the next slot in the compacted prefix, finishing in O(n) time and O(1) space.
- Opposite ends (converging pointers):
left = 0starts at the first index andright = n - 1at the last. The loop runswhile (left < right)(orleft <= right). Use this for symmetry problems (palindrome checking, array reversal) and sorted pair/extremum problems (pair sum, squaring a sorted array, container with most water). - Same direction (read/write or fast/slow pointers): Both
write = 0andread = 0start at index0.readscans every element whilewriteadvances only when a condition is met. Use this for in-place array compaction (removing duplicates, moving zeros, filtering a value while keeping relative order). - Two separate sequences:
i = 0points into arrayaandj = 0points into arrayb. At each step you advance whichever pointer holds the smaller element. Use this for merging sorted arrays or finding sorted intersections.
When the data must be sorted (and when sorting breaks the problem)
Converging pointers rely on a monotonic order to decide which pointer to move.
Example 4 · Why converging pair-sum requires sorted data
import java.util.Arrays;
public class SortingRequirementDemo { public static boolean hasPairWithSumTwoPointers(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left < right) { int sum = nums[left] + nums[right]; if (sum == target) { return true; } else if (sum < target) { left++; } else { right--; } } return false; }
public static void main(String[] args) { int[] unsorted = {2, 8, 1, 5}; // 2 + 8 = 10 exists! System.out.println("On unsorted [2,8,1,5] for target 10: " + hasPairWithSumTwoPointers(unsorted, 10));
int[] sorted = Arrays.copyOf(unsorted, unsorted.length); Arrays.sort(sorted); // [1, 2, 5, 8] System.out.println("On sorted [1,2,5,8] for target 10: " + hasPairWithSumTwoPointers(sorted, 10)); }}On unsorted [2,8,1,5] for target 10: false On sorted [1,2,5,8] for target 10: true
What this code does
- On unsorted
[2, 8, 1, 5], the first check2 + 5 = 7 < 10incrementsleftpast2, permanently missing the pair2 + 8 = 10. - After sorting into
[1, 2, 5, 8],1 + 8 = 9 < 10movesleftto2, and2 + 8 = 10finds the valid pair.
For example, in a sorted array nums = [1, 3, 4, 7, 10], if nums[left] + nums[right] is too small, moving left++ is guaranteed to increase (or keep equal) the sum, and moving right-- is guaranteed to decrease (or keep equal) the sum. On an unsorted array [7, 1, 10, 3, 4], moving left++ could make the sum jump up or down unpredictably, so converging pair-sum fails unless you sort first.
However, you cannot blindly sort the input if the problem asks you to return original array indices (because sorting scrambles positions, unless you store (value, originalIndex) pairs in O(n) space) or if the problem is about contiguous subarrays of an unsorted array. By contrast, symmetry checks (like palindromes) and same-direction compaction (like moving zeros) do not require sorted data.
How to spot this pattern
Look for these clues in the problem statement.
- The array is sorted (or may be sorted) and you need a pair, a triplet or a closest value: use pointers from both ends.
- The task must be done in place with O(1) extra space and the order kept (remove, compact, move zeros): use a read pointer and a write pointer.
- Two sorted arrays or lists must be merged or intersected: use one pointer in each.
- The statement checks symmetry (palindrome, mirror, reverse): compare from both ends and move inward.
Next step
Check your understanding
10 quick questions