Published

Two Pointers Technique: Patterns, Templates and 8 LeetCode Problems

The three kinds of two pointers, the signals that tell you which one to use, and eight worked LeetCode solutions with tested Python code.

On this page · 11 sections
  1. What is the two pointers technique?
  2. The three kinds of two pointers
  3. When to use two pointers: the signals
  4. Templates
  5. Why two pointers is O(n)
  6. Eight worked problems
  7. Two pointers vs sliding window vs hash map
  8. Common mistakes
  9. Practice problems by difficulty
  10. FAQ
  11. Learn it step by step

The two pointers technique solves array and string problems by moving two indices through the data instead of checking every pair. Checking all pairs costs O(n²); two pointers usually needs one O(n) pass, often with O(1) extra space. This guide covers the three shapes of two pointers, when each one applies, templates in Python and Java, and eight LeetCode problems with tested solutions.

What is the two pointers technique?

You keep two indices into the same array (or one index into each of two arrays) and move them based on what you see, so each step rules out work you would otherwise repeat. The trick is always the same: a comparison tells you which pointer can move without missing an answer.

In Two Sum II, for example, the array is sorted. If numbers[left] + numbers[right] is too small, no pair using numbers[left] with anything at or before right can reach the target, so left moves right. One comparison eliminates a whole row of pairs.

The three kinds of two pointers

KindPointers startThey moveTypical problems
Opposite endsleft = 0, right = n - 1Towards each otherPair sums in a sorted array, palindromes, container with most water, trapping rain water
Same direction (fast/slow, read/write)Both at the startSame way, at different speedsRemove duplicates, move zeroes, partitioning in place, linked list cycle
Two inputsOne pointer per array or listEach through its own inputMerge two sorted arrays, intersection of sorted arrays, is-subsequence

The sliding window is a fourth relative: two same-direction pointers where everything between them matters (a sum, a set of characters). It has its own guide: sliding window technique.

When to use two pointers: the signals

  • The input is sorted, or sorting it doesn’t break the problem (you need values, not original positions).
  • You’re looking for a pair or triplet with a target sum or difference.
  • The problem mentions palindromes, reversing, or comparing from both ends.
  • You must modify an array in place with O(1) extra space (remove, dedupe, partition).
  • Two sorted sequences need merging or comparing.

If you need original indices from an unsorted array (classic Two Sum, LeetCode 1), use a hash map instead: sorting would lose the positions.

Templates

Opposite ends

left, right = 0, len(a) - 1
while left < right:
    if condition_met(a[left], a[right]):
        record_answer()
        left += 1; right -= 1        # or return
    elif need_bigger(a[left], a[right]):
        left += 1
    else:
        right -= 1

Same direction (read/write)

write = 0
for read in range(len(a)):
    if keep(a[read]):
        a[write] = a[read]
        write += 1
# a[:write] is the result

Two inputs

i = j = 0
while i < len(a) and j < len(b):
    if a[i] < b[j]:
        i += 1
    elif a[i] > b[j]:
        j += 1
    else:
        handle_match(a[i]); i += 1; j += 1

In Java

import java.util.Arrays;

public class TwoPointers {
    // Opposite ends: Two Sum II on a sorted array (returns 1-indexed positions)
    static int[] twoSumSorted(int[] a, int target) {
        int left = 0, right = a.length - 1;
        while (left < right) {
            int sum = a[left] + a[right];
            if (sum == target) return new int[] {left + 1, right + 1};
            if (sum < target) left++;   // need a bigger sum
            else right--;               // need a smaller sum
        }
        return new int[0];
    }

    // Same direction: remove duplicates in place, return the new length
    static int removeDuplicates(int[] a) {
        if (a.length == 0) return 0;
        int write = 1;
        for (int read = 1; read < a.length; read++) {
            if (a[read] != a[write - 1]) a[write++] = a[read];
        }
        return write;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoSumSorted(new int[] {2, 7, 11, 15}, 9)));
        int[] a = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
        int k = removeDuplicates(a);
        System.out.println(k + " " + Arrays.toString(Arrays.copyOf(a, k)));
    }
}

Output:

[1, 2]
5 [0, 1, 2, 3, 4]

Why two pointers is O(n)

Each step moves at least one pointer, and no pointer ever moves backwards. With opposite ends, the gap right - left shrinks by at least one per step, so there are at most n steps. With read/write pointers, read visits each element once. So the scan is O(n) and uses O(1) extra space. If you sort first, the total becomes O(n log n), which is still far better than O(n²) pairs.

Eight worked problems

Every solution below is from one file that also checks each function against a brute force on 300 random inputs. Running it prints:

[1, 2]
[[-1, -1, 2], [-1, 0, 1]]
49
6
True False
5 [0, 1, 2, 3, 4]
[0, 1, 9, 16, 100]
[0, 0, 1, 1, 2, 2]
300 random cases per problem match brute force

1. Two Sum II, Input Array Is Sorted (LeetCode 167): opposite ends

The template in its purest form. Too small: move left. Too big: move right.

# 167. Two Sum II - Input Array Is Sorted (opposite ends)
def two_sum_sorted(numbers, target):
    left, right = 0, len(numbers) - 1
    while left < right:
        s = numbers[left] + numbers[right]
        if s == target:
            return [left + 1, right + 1]  # 1-indexed, as LeetCode asks
        if s < target:
            left += 1   # need a bigger sum
        else:
            right -= 1  # need a smaller sum
    return []

two_sum_sorted([2, 7, 11, 15], 9) → [1, 2]. O(n) time, O(1) space, versus O(n) space for the hash-map version.

2. 3Sum (LeetCode 15): sort, fix one, then two pointers

Sort, then for each nums[i] run Two Sum II on the rest with target -nums[i]. The fiddly part is duplicates: skip a first value equal to the previous one, and after a match skip second values equal to the previous one.

# 15. 3Sum (sort, fix one, two pointers on the rest)
def three_sum(nums):
    nums = sorted(nums)
    out = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue  # skip duplicate first values
        left, right = i + 1, len(nums) - 1
        while left < right:
            s = nums[i] + nums[left] + nums[right]
            if s < 0:
                left += 1
            elif s > 0:
                right -= 1
            else:
                out.append([nums[i], nums[left], nums[right]])
                left += 1
                right -= 1
                while left < right and nums[left] == nums[left - 1]:
                    left += 1  # skip duplicate second values
    return out

[-1, 0, 1, 2, -1, -4] → [[-1, -1, 2], [-1, 0, 1]]. O(n²) overall, which is optimal for 3Sum in practice. 4Sum (LeetCode 18) adds one more outer loop.

3. Container With Most Water (LeetCode 11): move the shorter wall

The area is limited by the shorter wall. Moving the taller wall inwards can only shrink the width without raising the limit, so it can never help. Move the shorter one.

# 11. Container With Most Water (move the shorter wall)
def max_area(height):
    left, right, best = 0, len(height) - 1, 0
    while left < right:
        best = max(best, (right - left) * min(height[left], height[right]))
        if height[left] < height[right]:
            left += 1
        else:
            right -= 1
    return best

[1, 8, 6, 2, 5, 4, 8, 3, 7] → 49.

4. Trapping Rain Water (LeetCode 42): running max from each side

Water above a bar is min(max on its left, max on its right) - height. Whichever side currently has the lower wall is the limit for that side’s next bar, so process that side and move it inwards. No extra arrays needed.

# 42. Trapping Rain Water (running max from each side)
def trap(height):
    left, right = 0, len(height) - 1
    left_max = right_max = water = 0
    while left < right:
        if height[left] < height[right]:
            left_max = max(left_max, height[left])
            water += left_max - height[left]
            left += 1
        else:
            right_max = max(right_max, height[right])
            water += right_max - height[right]
            right -= 1
    return water

[0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] → 6. The prefix-max/suffix-max version uses O(n) space; this uses O(1).

5. Valid Palindrome (LeetCode 125): skip what doesn’t count

Compare from both ends, skipping characters that aren’t letters or digits, case-insensitively.

# 125. Valid Palindrome (skip non-alphanumeric characters)
def is_palindrome(s):
    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

"A man, a plan, a canal: Panama" → True, "race a car" → False. Valid Palindrome II (LeetCode 680) allows one deletion: on the first mismatch, check both “skip left” and “skip right” with the same loop.

6. Remove Duplicates from Sorted Array (LeetCode 26): read/write pointers

read scans every element; write marks where the next unique value goes. Because the array is sorted, a value is new exactly when it differs from the last one written.

# 26. Remove Duplicates from Sorted Array (slow writer, fast reader)
def remove_duplicates(nums):
    if not nums:
        return 0
    write = 1
    for read in range(1, len(nums)):
        if nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1
    return write

[0, 0, 1, 1, 1, 2, 2, 3, 3, 4] → length 5, [0, 1, 2, 3, 4]. Move Zeroes (LeetCode 283) and Remove Element (LeetCode 27) are the same template with a different keep test.

7. Squares of a Sorted Array (LeetCode 977): fill from the back

With negative numbers, the largest square is at one of the two ends. Compare the ends, place the larger square at the back of the output, and move that pointer.

# 977. Squares of a Sorted Array (fill the result from the back)
def sorted_squares(nums):
    out = [0] * len(nums)
    left, right = 0, len(nums) - 1
    for k in range(len(nums) - 1, -1, -1):
        if abs(nums[left]) > abs(nums[right]):
            out[k] = nums[left] ** 2
            left += 1
        else:
            out[k] = nums[right] ** 2
            right -= 1
    return out

[-4, -1, 0, 3, 10] → [0, 1, 9, 16, 100] in O(n) instead of squaring and sorting in O(n log n).

8. Sort Colors (LeetCode 75): three pointers

The Dutch national flag partition. Everything before low is 0, everything after high is 2, and mid scans the unknown middle. When you swap a 2 to the back, don’t advance mid: the value you swapped in hasn’t been checked yet.

# 75. Sort Colors (Dutch national flag: three pointers)
def sort_colors(nums):
    low, mid, high = 0, 0, len(nums) - 1
    while mid <= high:
        if nums[mid] == 0:
            nums[low], nums[mid] = nums[mid], nums[low]
            low += 1
            mid += 1
        elif nums[mid] == 1:
            mid += 1
        else:
            nums[mid], nums[high] = nums[high], nums[mid]
            high -= 1  # don't advance mid: the swapped-in value is unchecked

[2, 0, 2, 1, 1, 0] → [0, 0, 1, 1, 2, 2] in one pass. The same three-way partition is what makes quicksort fast on arrays with many duplicates.

Two pointers vs sliding window vs hash map

UseWhen
Two pointers (opposite ends)Sorted input, pair/triplet conditions, palindromes, “which side to move” reasoning
Two pointers (read/write)In-place filtering, deduplication or partitioning
Sliding windowA condition on a contiguous range: longest/shortest substring or subarray
Hash mapUnsorted input where you need original indices, or counting complements (LeetCode 1, 560)

Common mistakes

  • while left <= right when you need two different elements. For pairs, use left < right; <= lets a pointer pair with itself.
  • Forgetting duplicates in 3Sum and 4Sum, which produces repeated triplets.
  • Sorting when indices matter. Sorting destroys original positions; LeetCode 1 needs a hash map.
  • Advancing mid after swapping with high in Sort Colors.
  • Moving the wrong pointer in Container With Most Water: always the shorter wall.

Practice problems by difficulty

ProblemKindDifficulty
125. Valid PalindromeOpposite endsEasy
26. Remove Duplicates from Sorted ArrayRead/writeEasy
283. Move ZeroesRead/writeEasy
977. Squares of a Sorted ArrayOpposite endsEasy
88. Merge Sorted ArrayTwo inputs (from the back)Easy
392. Is SubsequenceTwo inputsEasy
680. Valid Palindrome IIOpposite endsEasy
167. Two Sum IIOpposite endsMedium
15. 3SumSort + opposite endsMedium
11. Container With Most WaterOpposite endsMedium
75. Sort ColorsThree pointersMedium
18. 4SumSort + opposite endsMedium
42. Trapping Rain WaterOpposite endsHard

These also appear, with progress tracking, on the Blind 75, LeetCode 150 and DSA sheet. The DSA patterns sheet lists every two pointers problem we track.

FAQ

What is the two pointers technique in simple words?

Two indices move through an array (or two arrays) and each comparison tells you which index can safely move. It replaces checking every pair, O(n²), with a single pass, O(n).

Does two pointers only work on sorted arrays?

Opposite-end two pointers usually needs sorted input (or a symmetric property like palindromes). Read/write pointers and fast/slow pointers work on unsorted data, such as moving zeroes or detecting a linked list cycle.

What’s the difference between two pointers and sliding window?

A sliding window is two same-direction pointers where you track everything between them. Classic two pointers often looks only at the two elements under the pointers, and the pointers often start at opposite ends.

What is the time complexity of two pointers?

O(n) for the scan with O(1) extra space, because every step moves a pointer forward and none moves back. If you sort first, it’s O(n log n) overall.

Learn it step by step