Two Pointers Technique: Opposite-Direction Patterns Explained

Learn the two pointers technique for sorted pair sum, palindromes, container with most water, and 3Sum, with proofs and tested Python and Java code.

Executive Summary: The two pointers technique places one index at each end of a sequence and moves them toward each other, turning many quadratic pair searches into a single linear pass. It works because each move safely discards a whole group of candidate pairs, not because the input happens to be sorted. Learn that elimination argument once and sorted pair sum, palindromes, container with most water, and 3Sum all become the same loop.
Two pointers technique diagram with a left pointer and a right pointer moving toward each other across a sorted array

A candidate writes two nested loops to find a pair with a given sum in a sorted array of 100,000 numbers. The code is correct, and it checks about five billion pairs. The judge reports time limit exceeded. Then the interviewer points out that the code never used the sorted order, and asks what that order buys you.

The answer is the two pointers technique. Keep a left index at the start and a right index at the end. Look at the pair they point to, and move exactly one of them inward based on what you see. The loop stops when the pointers meet, so it runs at most n - 1 times. Here I cover the opposite-direction form, where the pointers start at the two ends and close in.

The code targets Python 3.12 and Java 21. You need two ideas. An array stores elements in one contiguous block, so reading index i costs constant time (see how arrays store elements in contiguous memory). Big-O notation describes how running time grows as the input grows, so O(n) means roughly proportional to n.

My position: learn the elimination argument, not the loop. Every correct opposite-direction solution answers one question at each step: which pointer cannot be part of a better answer? Move that one. If you cannot say why a move is safe, the code is a guess that happens to pass the sample.

How to recognize when you need the two pointers technique

The pattern hides behind a handful of recurring signals. Look for them in the input shape, the constraints, and the wording of the question.

  • A sorted array plus a pair condition. “Find two values that sum to a target” on sorted input is the textbook trigger. Sorted order tells you which direction makes the sum bigger or smaller.
  • Symmetry between the ends. Palindromes, reversing in place, and comparing the first and last characters all pair index i with index n - 1 - i.
  • An answer that depends on the distance between two indices. Container with most water scores a pair by width times the shorter height. Starting at maximum width and shrinking is the natural search order.
  • Triplets or quadruplets with a sum condition. Fix one element in an outer loop, then run a pair search on the rest. 3Sum becomes O(n^2) instead of O(n^3).
  • Constraints near 10^5 with an O(1) extra space hint. A quadratic pair scan will not finish in time, and a hash set may be ruled out by the memory requirement.

One warning sign points the other way. If the question asks for a contiguous subarray or substring with some property, both pointers usually move in the same direction. That is the sliding window family, and it has a different invariant.

The invariant: every move discards a whole row of pairs

Picture every candidate pair (i, j) with i < j as a cell in a triangle. A brute-force scan visits every cell. Two pointers visits one cell per step and proves that a full row or column of other cells holds no answer.

sorted nums:  [1]  [3]  [4]  [6]  [8]  [11]      target = 10
index:         0    1    2    3    4    5
               L                        R      1 + 11 = 12 > 10

Pair triangle (row = left index, column = right index):

          j=1  j=2  j=3  j=4  j=5
   i=0     .    .    .    .   12  <- too big: every pair (k, 5) with k >= 0
   i=1          .    .    .    x     is at least 12, so drop column 5
   i=2               .    .    x
   i=3                    .    x
   i=4                         x

Here is the argument for sorted pair sum. Suppose nums[left] + nums[right] is larger than the target. Every element between the pointers is at least nums[left], so pairing nums[right] with any of them gives a sum that is still too large. Column right is dead, and you decrement right. The mirror case kills row left when the sum is too small.

The invariant you maintain is simple. If a valid pair exists, both of its indices lie inside [left, right]. It holds at the start, each move preserves it, and the loop ends when the window is empty or a pair is found. That is the whole correctness proof.

The reusable template: sorted pair sum

The template below returns the indices of any pair that sums to the target, or None when no pair exists. The input must be sorted in non-decreasing order. The test block covers a normal case, empty and single-element arrays, duplicates, negative numbers, and the edge case where one element would have to be used twice.

In Python:

def pair_with_sum(nums: list[int], target: int) -> tuple[int, int] | None:
    """Return (i, j) with i < j and nums[i] + nums[j] == target, else None.

    nums must be sorted in non-decreasing order.
    """
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return left, right
        if total < target:
            left += 1   # row `left` cannot reach the target
        else:
            right -= 1  # column `right` always overshoots
    return None


if __name__ == "__main__":
    assert pair_with_sum([1, 3, 4, 6, 8, 11], 10) == (2, 3)
    assert pair_with_sum([], 5) is None
    assert pair_with_sum([5], 10) is None          # never pair an element with itself
    assert pair_with_sum([2, 2, 3, 3], 4) == (0, 1)  # duplicates form a valid pair
    assert pair_with_sum([-4, -1, 0, 2, 7], 1) == (1, 3)
    assert pair_with_sum([1, 2, 3], 100) is None
    print("PASS")

The same template in Java. The sum is computed as a long so that two large int values cannot overflow into a negative number:

import java.util.Arrays;

public class PairWithSum {
    // Returns {i, j} with i < j and nums[i] + nums[j] == target, or an empty array.
    static int[] pairWithSum(int[] nums, long target) {
        int left = 0, right = nums.length - 1;
        while (left < right) {
            long total = (long) nums[left] + nums[right];
            if (total == target) {
                return new int[] {left, right};
            }
            if (total < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[0];
    }

    static void check(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }

    public static void main(String[] args) {
        check(Arrays.equals(pairWithSum(new int[] {1, 3, 4, 6, 8, 11}, 10), new int[] {2, 3}), "normal");
        check(pairWithSum(new int[] {}, 5).length == 0, "empty");
        check(pairWithSum(new int[] {5}, 10).length == 0, "single element used twice");
        check(Arrays.equals(pairWithSum(new int[] {2, 2, 3, 3}, 4), new int[] {0, 1}), "duplicates");
        check(Arrays.equals(pairWithSum(new int[] {-4, -1, 0, 2, 7}, 1), new int[] {1, 3}), "negatives");
        int big = Integer.MAX_VALUE;
        check(Arrays.equals(pairWithSum(new int[] {1, big - 1, big}, 2L * big - 1), new int[] {1, 2}), "overflow");
        System.out.println("PASS");
    }
}

Dry run on a small input

Take nums = [1, 3, 4, 6, 8, 11] and target = 10. Each row is one iteration of the loop.

Step left right nums[left] + nums[right] Decision
1 0 5 1 + 11 = 12 Too big, drop column 5, right becomes 4
2 0 4 1 + 8 = 9 Too small, drop row 0, left becomes 1
3 1 4 3 + 8 = 11 Too big, right becomes 3
4 1 3 3 + 6 = 9 Too small, left becomes 2
5 2 3 4 + 6 = 10 Match, return (2, 3)

Five steps instead of fifteen pair checks. On sorted input with 100,000 elements, the loop runs at most 99,999 times. For unsorted input where you must report original positions, a hash map complement lookup for unsorted Two Sum is the better tool.

Valid palindrome: skipping characters without breaking the bounds

A palindrome reads the same forward and backward. The common interview version ignores case and anything that is not a letter or digit, so “Step on no pets!” counts. Sorting plays no role here. The invariant is that everything outside [left, right] has already been matched.

The trap is the skip step. If you skip punctuation with an inner while loop and forget the left < right bound, a string made only of punctuation runs the index off the end. The version below uses a single loop with three branches, so every move re-checks the bound.

In Python:

def is_clean_palindrome(s: str) -> bool:
    """True if s is a palindrome after dropping non-alphanumerics and ignoring case."""
    left, right = 0, len(s) - 1
    while left < right:
        if not s[left].isalnum():
            left += 1
        elif not s[right].isalnum():
            right -= 1
        elif s[left].lower() != s[right].lower():
            return False
        else:
            left += 1
            right -= 1
    return True


if __name__ == "__main__":
    assert is_clean_palindrome("Step on no pets!")
    assert is_clean_palindrome("Was it a car, or a cat I saw?")
    assert is_clean_palindrome("")
    assert is_clean_palindrome("x")
    assert is_clean_palindrome(".,!?")          # only punctuation: bounds must hold
    assert is_clean_palindrome("noon")          # duplicate letters in the middle
    assert not is_clean_palindrome("ab")
    assert not is_clean_palindrome("0P")        # digit vs letter, not equal
    print("PASS")

The same check in Java:

public class CleanPalindrome {
    static boolean isCleanPalindrome(String s) {
        int left = 0, right = s.length() - 1;
        while (left < right) {
            char a = s.charAt(left), b = s.charAt(right);
            if (!Character.isLetterOrDigit(a)) {
                left++;
            } else if (!Character.isLetterOrDigit(b)) {
                right--;
            } else if (Character.toLowerCase(a) != Character.toLowerCase(b)) {
                return false;
            } else {
                left++;
                right--;
            }
        }
        return true;
    }

    static void check(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }

    public static void main(String[] args) {
        check(isCleanPalindrome("Step on no pets!"), "normal");
        check(isCleanPalindrome("Was it a car, or a cat I saw?"), "sentence");
        check(isCleanPalindrome(""), "empty");
        check(isCleanPalindrome("x"), "single");
        check(isCleanPalindrome(".,!?"), "only punctuation");
        check(isCleanPalindrome("noon"), "duplicates");
        check(!isCleanPalindrome("ab"), "mismatch");
        check(!isCleanPalindrome("0P"), "digit vs letter");
        System.out.println("PASS");
    }
}

Both versions run in O(n) time in the worst case and use O(1) extra space. Building a cleaned copy and comparing it to its reverse also works, but it allocates O(n) extra memory.

Container with most water: why moving the shorter side is safe

You get a list of wall heights at evenly spaced positions. Pick two walls; the water they hold equals the distance between them times the shorter wall. Find the largest amount. The heights are not sorted, which is why this problem kills the myth that two pointers needs sorted input.

Start with the widest pair, the first and last walls. Then always move the pointer at the shorter wall. Here is the proof sketch. Say heights[left] <= heights[right]. Any other pair that keeps left uses some j between the pointers. Its width is smaller than the current width. Its height is at most heights[left], because the shorter wall caps the water. So every pair in row left holds no more water than the pair you just measured. You can drop the whole row and advance left.

Moving the taller side gives no such guarantee. The width shrinks, the cap stays at the short wall, and you may skip the optimum. That asymmetry is the whole problem.

In Python, with a brute-force cross-check on random inputs inside the tests:

import random
from itertools import combinations


def max_water(heights: list[int]) -> int:
    left, right = 0, len(heights) - 1
    best = 0
    while left < right:
        width = right - left
        if heights[left] <= heights[right]:
            best = max(best, heights[left] * width)
            left += 1    # row `left` cannot beat what we just measured
        else:
            best = max(best, heights[right] * width)
            right -= 1
    return best


def max_water_brute(heights: list[int]) -> int:
    return max((min(heights[i], heights[j]) * (j - i)
                for i, j in combinations(range(len(heights)), 2)), default=0)


if __name__ == "__main__":
    assert max_water([4, 8, 2, 6, 5, 7, 3]) == 28
    assert max_water([]) == 0
    assert max_water([9]) == 0
    assert max_water([5, 5, 5, 5]) == 15        # equal heights: either move is fine
    assert max_water([1, 1]) == 1
    rng = random.Random(42)
    for _ in range(500):
        hs = [rng.randint(0, 20) for _ in range(rng.randint(0, 12))]
        assert max_water(hs) == max_water_brute(hs), hs
    print("PASS")

The same algorithm in Java:

import java.util.Random;

public class MaxWater {
    static long maxWater(int[] heights) {
        int left = 0, right = heights.length - 1;
        long best = 0;
        while (left < right) {
            long width = right - left;
            if (heights[left] <= heights[right]) {
                best = Math.max(best, heights[left] * width);
                left++;
            } else {
                best = Math.max(best, heights[right] * width);
                right--;
            }
        }
        return best;
    }

    static long maxWaterBrute(int[] heights) {
        long best = 0;
        for (int i = 0; i < heights.length; i++) {
            for (int j = i + 1; j < heights.length; j++) {
                best = Math.max(best, (long) Math.min(heights[i], heights[j]) * (j - i));
            }
        }
        return best;
    }

    static void check(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }

    public static void main(String[] args) {
        check(maxWater(new int[] {4, 8, 2, 6, 5, 7, 3}) == 28, "normal");
        check(maxWater(new int[] {}) == 0, "empty");
        check(maxWater(new int[] {9}) == 0, "single");
        check(maxWater(new int[] {5, 5, 5, 5}) == 15, "equal heights");
        Random rng = new Random(42);
        for (int t = 0; t < 500; t++) {
            int[] hs = new int[rng.nextInt(13)];
            for (int i = 0; i < hs.length; i++) {
                hs[i] = rng.nextInt(21);
            }
            check(maxWater(hs) == maxWaterBrute(hs), "random case " + t);
        }
        System.out.println("PASS");
    }
}

Here is the trace for heights = [4, 8, 2, 6, 5, 7, 3]. Notice that the best pair, walls 8 and 7, is found at step 3 even though the pointers started far away from it.

Step left right Heights Width Water Best Move
1 0 6 4, 3 6 18 18 right (3 is shorter)
2 0 5 4, 7 5 20 20 left (4 is shorter)
3 1 5 8, 7 4 28 28 right
4 1 4 8, 5 3 15 28 right
5 1 3 8, 6 2 12 28 right
6 1 2 8, 2 1 2 28 right, pointers meet

A close cousin, trapping rain water, also runs on two pointers that track the tallest wall seen from each side. It has its own walkthrough comparing trapping rain water with a stack, two pointers, and prefix maxima.

3Sum: one fixed element plus a pair search, with duplicate skipping

The task: list every distinct triplet of values that sums to zero. Brute force checks all n choose 3 triplets in O(n^3) time. The faster approach sorts the array, fixes the smallest element of the triplet with index i, and runs the pair template on the slice to its right with target -nums[i].

Duplicates are where most solutions break. Sorted input [-2, -2, 0, 2, 2] contains the triplet [-2, 0, 2] once as values, but a naive loop reports it several times. You need two skips. First, skip an anchor value equal to the previous anchor. Second, after recording a triplet, advance left past every copy of the value you just used.

In Python:

import random
from itertools import combinations


def three_sum(nums: list[int]) -> list[list[int]]:
    nums = sorted(nums)
    n = len(nums)
    triples: list[list[int]] = []
    for i in range(n - 2):
        if nums[i] > 0:
            break                      # smallest value positive: no zero sum left
        if i > 0 and nums[i] == nums[i - 1]:
            continue                   # same anchor value as last time
        left, right = i + 1, n - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total < 0:
                left += 1
            elif total > 0:
                right -= 1
            else:
                triples.append([nums[i], nums[left], nums[right]])
                left += 1
                right -= 1
                while left < right and nums[left] == nums[left - 1]:
                    left += 1          # skip copies of the value just used
    return triples


def three_sum_brute(nums: list[int]) -> list[list[int]]:
    found = {tuple(sorted(c)) for c in combinations(nums, 3) if sum(c) == 0}
    return [list(t) for t in sorted(found)]


if __name__ == "__main__":
    assert three_sum([-3, 0, 1, 2, -1, 1, -2]) == [[-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1]]
    assert three_sum([]) == []
    assert three_sum([0]) == []
    assert three_sum([0, 0, 0, 0]) == [[0, 0, 0]]
    assert three_sum([-2, -2, 0, 2, 2]) == [[-2, 0, 2]]
    rng = random.Random(7)
    for _ in range(300):
        xs = [rng.randint(-5, 5) for _ in range(rng.randint(0, 10))]
        assert three_sum(xs) == three_sum_brute(xs), xs
    print("PASS")

The same solution in Java:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {
    static List<List<Integer>> threeSum(int[] input) {
        int[] nums = input.clone();
        Arrays.sort(nums);
        int n = nums.length;
        List<List<Integer>> triples = new ArrayList<>();
        for (int i = 0; i < n - 2; i++) {
            if (nums[i] > 0) {
                break;
            }
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int left = i + 1, right = n - 1;
            while (left < right) {
                long total = (long) nums[i] + nums[left] + nums[right];
                if (total < 0) {
                    left++;
                } else if (total > 0) {
                    right--;
                } else {
                    triples.add(List.of(nums[i], nums[left], nums[right]));
                    left++;
                    right--;
                    while (left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }
                }
            }
        }
        return triples;
    }

    static void check(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> expected = List.of(
            List.of(-3, 1, 2), List.of(-2, 0, 2), List.of(-2, 1, 1), List.of(-1, 0, 1));
        check(threeSum(new int[] {-3, 0, 1, 2, -1, 1, -2}).equals(expected), "normal");
        check(threeSum(new int[] {}).isEmpty(), "empty");
        check(threeSum(new int[] {0}).isEmpty(), "single");
        check(threeSum(new int[] {0, 0, 0, 0}).equals(List.of(List.of(0, 0, 0))), "all zeros");
        check(threeSum(new int[] {-2, -2, 0, 2, 2}).equals(List.of(List.of(-2, 0, 2))), "duplicates");
        System.out.println("PASS");
    }
}

The pair search inside each anchor is linear, so the total is O(n^2) time in the worst case. Sorting adds O(n log n), which the quadratic term dominates. The same structure extends to 4Sum with two nested anchors and O(n^3) time.

Complexity of the two pointers technique

Every opposite-direction loop moves at least one pointer per iteration, and the gap between them starts at n - 1. So the core loop runs at most n - 1 times. The table separates the loop cost from any sorting you add.

Problem Time (worst case) Extra space Notes
Pair sum, already sorted O(n) O(1) Brute force is O(n^2)
Pair sum, unsorted input O(n log n) Depends on the sort Sorting loses original indices
Valid palindrome O(n) O(1) No sorting involved
Container with most water O(n) O(1) Brute force is O(n^2)
3Sum O(n^2) Sort space plus output Brute force is O(n^3)

“Depends on the sort” is not a dodge. CPython’s list.sort can need a temporary array of up to n / 2 pointers for merging. Java sorts int[] with a Dual-Pivot Quicksort, as the Java 21 Arrays documentation states. If an interviewer insists on O(1) extra space, ask whether the sort counts.

You can measure the gap yourself. This script times brute force against the template on 3,000 sorted values with no valid pair, so both versions do their maximum work:

import random
import timeit


def pair_brute(nums: list[int], target: int) -> tuple[int, int] | None:
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return i, j
    return None


def pair_with_sum(nums: list[int], target: int) -> tuple[int, int] | None:
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return left, right
        if total < target:
            left += 1
        else:
            right -= 1
    return None


if __name__ == "__main__":
    rng = random.Random(1)
    nums = sorted(rng.sample(range(1, 10**6), 3000))
    target = -1                                   # impossible: forces a full scan
    assert pair_brute(nums, target) is None and pair_with_sum(nums, target) is None
    for name, fn in (("brute force", pair_brute), ("two pointers", pair_with_sum)):
        seconds = timeit.timeit(lambda: fn(nums, target), number=1)
        print(f"{name:13} {seconds:.4f} s")

Run it, then double the size to 6,000. The brute-force time should roughly quadruple while the two-pointer time roughly doubles. Your absolute numbers depend on your machine, but the growth rates do not.

Where this shows up in real systems

  • Reversing a Python list. CPython’s list.reverse() calls a helper named reverse_slice that swaps *lo and *hi and moves them toward each other until they meet, as the CPython 3.12 listobject.c source shows. It is the palindrome loop with a swap instead of a comparison.
  • Sorting descending runs. The same file shows list.sort detecting runs and reversing strictly descending runs in place with that helper. The source comment explains that the run must be strictly descending so that reversing it cannot reorder equal elements and break stability.
  • Reversing a Java linked list. In the OpenJDK 21 Collections.java source, Collections.reverse swaps indices i and j for random-access lists. For a large sequential list, it uses one forward and one backward ListIterator instead. Opposite-direction pointers work on any structure that can step backward, including a doubly linked list.
  • Quicksort partitioning. In the OpenJDK 21 DualPivotQuicksort.java source, partitioning advances a lower index from the left and an upper index from the right past elements already on the correct side. Partition schemes use the same elimination idea: each skipped element is proven to be in place.

How to explain it in an interview

Talk through the solution in a fixed order. Interviewers grade the reasoning as much as the code.

  1. Brute force first. “Checking every pair is O(n^2). At n = 10^5 that is about five billion pairs, too slow.”
  2. Name the bottleneck. “The brute force ignores that the array is sorted.”
  3. State the insight as an elimination. “If the sum is too big, the right element is too big for every remaining partner, so I can drop it.”
  4. Write the template. Keep while left < right and one move per branch.
  5. Give the complexity with its case. O(n) time in the worst case, O(1) extra space, plus the sort if the input arrives unsorted.
  6. Walk the edge cases. Empty input, one element, duplicates, negative values, and overflow in Java.

Expect these follow-ups. “What if the array is not sorted and you need the original indices?” Switch to a hash map, or sort index pairs. “How would you count pairs whose sum is below the target?” When nums[left] + nums[right] is below it, every partner between them also works, so add right - left in one step and advance left. “Can you avoid duplicate triplets without a set?” Show the two skips.

A mistake I see often when candidates solve container with most water: they move the shorter wall because they remember the trick, but they cannot say why. When I ask what happens if they move the taller wall instead, the answer falls apart. A strong answer states the bound: every pair that keeps the shorter wall is narrower and no taller, so none can win. That single sentence separates a memorized answer from an understood one.

A decision framework for pair and partner problems

  1. Is the answer a contiguous range? If yes, you probably want same-direction pointers or a sliding window, not opposite-direction pointers.
  2. Is the input sorted, or can you sort it without losing what you must return? If yes, opposite-direction pointers give O(n) time and O(1) extra space.
  3. Must you return original indices from unsorted data? Use a hash map: O(n) average time, O(n) space.
  4. Is the problem symmetric around the middle? Palindromes and in-place reversal use opposite-direction pointers with no sorting at all.
  5. Is there one fixed element plus a pair? Sort once, loop the anchor, and run the pair template inside: O(n^2) for triplets.
  6. Do you need many queries against one sorted array? For a single target, two pointers wins. For many different lookups, binary search on a sorted array answers each one in O(log n).

When not to use opposite-direction pointers

  • Unsorted input where positions matter. Sorting costs O(n log n) and scrambles indices. A single pass with a hash map is simpler and faster on average.
  • Contiguous subarray questions. “Longest substring without repeats” or “shortest subarray with sum at least k” need a window whose two ends both move forward. Opposite-direction pointers have no valid elimination rule there. For in-place filtering, such as removing duplicates, use same-direction read and write pointers.
  • Singly linked lists. You cannot step backward from the tail, so a right pointer has nowhere to go. Copy to an array, reverse half the list, or use a fast and slow pointer pair.

Common mistakes

  • Using left <= right for pairs. The loop then pairs an element with itself. Input [5] with target 10 returns (0, 0) instead of nothing.
  • Forgetting to sort. The elimination argument assumes order. On [9, 3, 1, 5] with target 8, the loop pairs 9 with 5, 1, and 3, finds every sum too big, and never tests 3 with 5.
  • Moving the taller wall. On [4, 8, 2, 6, 5, 7, 3], always moving the taller side throws away the wall of height 8 early and returns 18 instead of 28.
  • Skipping duplicates in the wrong place. Checking nums[i] == nums[i + 1] for the anchor skips the first copy, not the second, and loses triplets like [-1, -1, 2].
  • Integer overflow in Java. Adding two values near Integer.MAX_VALUE wraps to a negative number, so the loop moves the wrong pointer. Cast to long before adding.
  • Unbounded skip loops. An inner while not s[left].isalnum() without left < right raises IndexError on ".,!?".

The anchor-skip bug deserves a closer look. The wrong version compares with the next element:

for i in range(n - 2):
    if nums[i] == nums[i + 1]:   # WRONG: skips the first copy of the anchor
        continue

The right version compares with the previous element:

for i in range(n - 2):
    if i > 0 and nums[i] == nums[i - 1]:   # RIGHT: skips later copies only
        continue

On sorted input [-1, -1, 2], index 0 is the only anchor with two elements to its right. The wrong version skips it and finds nothing. The right version anchors at index 0, where both -1 and 2 remain available, and finds the triplet.

Practice problems

Problem Difficulty The twist
Reverse String Easy Swap instead of compare; the loop body is the whole solution
Valid Palindrome Easy Skip non-alphanumeric characters while keeping the bound check
Two Sum II (sorted input) Easy The template as written, returning positions
Squares of a Sorted Array Easy Largest square sits at one of the ends; fill the output from the back
Valid Palindrome II Medium On the first mismatch, try skipping either side once
Container With Most Water Medium Score depends on width; move the shorter wall
3Sum Medium Anchor loop plus two duplicate skips
3Sum Closest Medium Track the smallest absolute gap instead of an exact match

Key takeaways

  • Before writing the loop, state which pointer cannot be part of a better answer. That sentence is your proof.
  • Keep the invariant “any answer lies inside [left, right]” and use while left < right for pair problems.
  • Sortedness is one source of an elimination rule, not a requirement. Palindromes and container with most water use other rules.
  • Count the sort. Pair sum on unsorted input costs O(n log n), and the sort may need extra memory.
  • For 3Sum, skip repeated anchors by comparing with the previous element, and skip repeated left values after each match.
  • In Java, compute pair sums as long.
  • Cross-check against brute force on random small inputs before you trust a new move rule.

Frequently Asked Questions

Does the two pointers technique only work on sorted arrays?

No. Sorted order is one way to prove that a pointer move is safe, but palindrome checks and container with most water work on unsorted input. What you need is a rule that rules out every pair using the pointer you move.

What is the time complexity of the two pointers approach?

The core opposite-direction loop runs in O(n) time in the worst case because the gap between the pointers shrinks by at least one each step. If you must sort first, the total becomes O(n log n). 3Sum runs the loop once per anchor, so it takes quadratic time.

Why do you move the shorter line in container with most water?

The shorter wall caps the water for every pair that includes it, and every other partner is closer, so none of those pairs can hold more. Dropping the shorter wall loses nothing. Moving the taller wall gives no such guarantee.

Should I use two pointers or a hash map for Two Sum?

Use a hash map when the input is unsorted and you must return original indices, since it runs in linear average time. Use two pointers when the input is already sorted or when you need constant extra space.

Move the pointer that cannot improve the answer

Every opposite-direction problem reduces to one decision per step: which end is provably useless now? In pair sum it is the end that overshoots or undershoots. In container with most water it is the shorter wall, and in palindromes it is the pair you just matched. Find that rule, prove it in one sentence, and the code writes itself. You can find the other patterns in the DSA Playbook.

Rule of thumb: if you cannot explain why a pointer moves, you have not solved the problem yet.

Originally posted on 3 December 2026 and post last modified on 3 December 2026

Algorithms Coding Interviews Two Pointers

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *