Two Pointers

Two pointers means keeping two indexes into an array or string and moving them according to a simple rule, instead of checking every pair with nested loops. The pointers either start at opposite ends and walk toward each other, or move in the same direction at different speeds. Interviewers like it because it turns many O(n^2) brute-force ideas into clean O(n) solutions, and it tests whether you can explain why moving a pointer is safe.

When to use it

  • The array or string is sorted (or can be sorted first) and you need to find a pair or triple with a target sum.
  • You are asked to check something that reads the same from both ends, like a palindrome.
  • The problem says to modify an array in place, for example removing duplicates or moving zeros, using O(1) extra space.
  • You need to find a pair that maximizes or minimizes something, such as the container that holds the most water.
  • A linked list question asks about the middle, a cycle, or the k-th node from the end, which suggests a slow and a fast pointer.

See it work

  1. Problem: in the sorted array [1, 3, 4, 6, 8, 11], find two numbers that add up to 10. Put one pointer at the start (left = 0) and one at the end (right = 5). [1, 3, 4, 6, 8, 11]
  2. Add the two values: 1 + 11 = 12. That is bigger than 10. Since the array is sorted, the 11 can only get bigger sums with anything to its right, and the smallest partner is already 1. So 11 can never be part of the answer. Move right one step left. [1, 3, 4, 6, 8, 11]
  3. Now 1 + 8 = 9. That is smaller than 10. The 1 is too small to ever reach 10 with any remaining number (8 is the biggest one left). So discard 1 by moving left one step right. [1, 3, 4, 6, 8, 11]
  4. Now 3 + 8 = 11, which is too big again. Move right one step left to drop the 8. [1, 3, 4, 6, 8, 11]
  5. Now 3 + 6 = 9, too small. Move left to the right to drop the 3. [1, 3, 4, 6, 8, 11]
  6. Finally 4 + 6 = 10, which is the target. We found the pair at indexes 2 and 3 after only 6 checks. Brute force would have looked at up to 15 pairs, and the gap grows fast for bigger arrays. [1, 3, 4, 6, 8, 11]

Code template

Python

def two_pointers(nums, target):
    left, right = 0, len(nums) - 1   # start at both ends (nums is sorted)
    while left < right:              # stop when they meet
        total = nums[left] + nums[right]
        if total == target:
            return [left, right]     # found a valid pair
        elif total < target:
            left += 1                # need a bigger sum: move the small end up
        else:
            right -= 1               # need a smaller sum: move the big end down
    return [-1, -1]                  # no pair exists

C

// Returns 1 and fills *i, *j if a pair is found, otherwise 0.
int two_pointers(const int *nums, int n, int target, int *i, int *j) {
    int left = 0, right = n - 1;      // start at both ends (nums is sorted)
    while (left < right) {            // stop when they meet
        int total = nums[left] + nums[right];
        if (total == target) {
            *i = left; *j = right;    // found a valid pair
            return 1;
        } else if (total < target) {
            left++;                   // need a bigger sum: move the small end up
        } else {
            right--;                  // need a smaller sum: move the big end down
        }
    }
    return 0;                         // no pair exists
}

Java

int[] twoPointers(int[] nums, int target) {
    int left = 0, right = nums.length - 1; // start at both ends (nums is sorted)
    while (left < right) {                 // stop when they meet
        int total = nums[left] + nums[right];
        if (total == target) {
            return new int[]{left, right}; // found a valid pair
        } else if (total < target) {
            left++;                        // need a bigger sum: move the small end up
        } else {
            right--;                       // need a smaller sum: move the big end down
        }
    }
    return new int[]{-1, -1};              // no pair exists
}

Complexity: Time is O(n) because each pointer only moves in one direction and the two together take at most n steps (O(n log n) if you must sort first). Extra space is O(1).

Programs that use it

Interview problems that use it

  • Two Sum in a sorted array: Start at both ends and move the left pointer up when the sum is too small or the right pointer down when it is too big until the sum matches.
  • Valid Palindrome: Compare the characters at the left and right pointers (skipping non-letters), then move both inward; any mismatch means it is not a palindrome.
  • Container With Most Water: Compute the area between the two lines, then move the pointer at the shorter line inward, because only a taller line can improve the area.
  • 3Sum (find all triples that add to zero): Sort the array, fix one number, then run the two-pointer pair search on the rest while skipping duplicate values.
  • Remove Duplicates from a Sorted Array: Use a slow pointer for where the next unique value goes and a fast pointer that scans ahead, copying a value only when it differs from the last one kept.
  • Linked List Cycle: Move a slow pointer one step and a fast pointer two steps; if there is a cycle the fast pointer eventually lands on the slow one.

Common mistakes

  • Using opposite-end pointers on an unsorted array. The 'move left up or right down' logic only works because sorted order tells you which direction changes the sum, so sort first or pick another approach like a hash map.
  • Getting the loop condition wrong. With pairs you need left < right, not left <= right, otherwise you can pair an element with itself; with some in-place problems the condition must be different, so check it on a tiny example.
  • Forgetting to skip duplicates or to move a pointer after a match. In problems like 3Sum, not skipping repeated values gives duplicate answers, and not moving a pointer after recording a result can cause an infinite loop.

Frequently asked questions

When should I use two pointers instead of a hash map?

Use two pointers when the data is sorted or can be sorted cheaply and you want O(1) extra space. A hash map works on unsorted data in O(n) time but uses O(n) memory. If the interviewer asks for constant space, two pointers is usually the expected answer.

What is the difference between two pointers and sliding window?

A sliding window is a special case of two pointers where both move left to right and the stretch between them is the thing you are tracking, such as the longest substring without repeats. In classic two pointers the pointers often start at opposite ends or the problem is about pairs, not a continuous range.

Why is two pointers O(n) when there is a loop inside a loop in some solutions?

Each pointer only moves forward (or only backward) and never resets, so the total number of moves is at most about n. In 3Sum there is an outer loop over n values with an O(n) inner scan, so the whole thing is O(n^2), which is still better than the O(n^3) brute force.

← All interview patterns

Try AI Flowchart free →