Skip to content
Visual explainer 3h to learn 4 steps

Two pointers

Replace nested loops with converging or same-direction pointers on sorted arrays and lists.

By Invicly Tech, , in Data Structures & Algorithms. About 13 minutes to read.

Topic 48 of 54

In short

The two-pointer pattern moves two indexes through a sequence, either towards each other from both ends or in the same direction at different speeds. On sorted data it replaces an O(n^2) pair search with an O(n) scan. It also powers in-place deduplication and partitioning.

Explained simply

Many array problems are about pairs: two numbers that add up to a target, or two walls that hold the most water. The slow way checks every pair, which is about n times n steps. With two pointers you keep two positions (indexes) in the array and move them in a smart way, so you look at each element only a few times.

The most common shape puts one pointer at the start and one at the end, and moves them toward each other. This works when the array is sorted, because the order tells you which way to move. If the sum is too small, move the left pointer right to get a bigger number. If it is too big, move the right pointer left.

The second shape moves both pointers in the same direction. A read pointer looks at every element, and a write pointer marks where the next element you keep should go. This lets you remove duplicates or filter an array in place, without making a second array.

A third shape is fast and slow: one pointer moves two steps at a time, the other moves one. In a linked list with a loop, the fast pointer will catch the slow one. If there is no loop, the fast pointer simply reaches the end first.

Press Play on a diagram to walk through it one step at a time.

FlowPair with target sum on sorted input
  1. 1
    Start

    left = 0, right = n - 1.

  2. 2
    Sum

    s = a[left] + a[right].

  3. 3
    Too small

    left += 1.

  4. 4
    Too big

    right -= 1.

  5. 5
    Equal

    Found the pair.

MapThe three shapes of two pointers
Two pointers
  • Converging
    • Pair sum on sorted array
    • Three-sum
    • Container with most water
    • Valid palindrome
  • Same direction
    • Remove duplicates
    • Move zeros
    • Merge two sorted arrays
  • Fast and slow
    • Linked list cycle
    • Middle of a list
    • Find the duplicate number
CompareTwo ways to find a pair with a given sum
Hash set
  • O(n) time
  • O(n) extra memory
  • Works on unsorted input
  • Keeps original indexes
Sort plus two pointers
  • O(n log n) with the sort
  • O(1) extra if sorting in place
  • O(n) if already sorted
  • Original indexes are lost after sorting

In depth

Why skipping pairs is safe

Converging pointers look at only n - 1 pairs out of about n^2 / 2, so you need a reason why the skipped pairs cannot be the answer. The reason is elimination. Suppose the array is sorted and a[left] + a[right] is less than the target. Every other partner for a[left] that is still in play sits at an index below right, so it is no larger than a[right]. All those sums are also too small, so a[left] can never be in a solution. You drop it for good with left += 1.

The same argument works the other way when the sum is too big: a[right] is dropped. Each step removes one element forever, so the loop runs at most n - 1 times. Saying this out loud in an interview is what turns a guess into a proof.

  • Each step discards one element permanently
  • At most n - 1 steps, so O(n) time
  • The proof needs sorted order (or another monotonic rule)

Three-sum without repeated triplets

Three-sum asks for all unique triplets that add up to 0. Sort first, in O(n log n). Then fix the first element a[i] and run converging pointers on the part to its right, looking for a pair that sums to -a[i]. Each fixed i costs O(n), so the total is O(n^2). That is the expected answer; no known approach is much faster in general.

Duplicates are where most bugs live. Skip i when a[i] equals a[i - 1], because that first value was already tried. After you record a triplet, move both pointers inward, then keep moving left while it equals the value you just used. You can also stop early: once a[i] is greater than 0, every later sum is positive.

The same idea extends to four-sum with two fixed loops and O(n^3) time. In general k-sum this way costs O(n^(k-1)).

FlowThree-sum on sorted input
  1. 1
    Sort

    O(n log n), once.

  2. 2
    Fix a[i]

    Skip it if it equals a[i - 1].

  3. 3
    Two pointers

    Find pairs summing to -a[i] in a[i+1..].

  4. 4
    Record hit

    Move both pointers, skip equal values.

  5. 5
    Next i

    Stop early once a[i] is above 0.

Container with most water: move the shorter wall

You get heights h[0..n-1] and want two lines that, with the x-axis, hold the most water. The area of a pair is min(h[left], h[right]) * (right - left). Start with the widest pair and move inward.

Why move the shorter wall? Say h[left] is the shorter one. Any pair that keeps left and moves right inward has a smaller width, and its height is still capped by h[left]. So none of those pairs can beat the area you just measured, and left can be discarded. Moving the taller wall would throw away nothing useful and might skip the best pair. When both walls are equal you may move either one.

The result is O(n) time and O(1) space, against O(n^2) for trying every pair.

Same-direction pointers: filter and partition in place

The read and write pattern keeps a[0..w-1] as the finished part. For every r from left to right, if a[r] should be kept, copy it to a[w] and add 1 to w. At the end, w is the new length. This removes duplicates from a sorted array (keep a[r] if it differs from a[w - 1]) and moves zeros to the end (keep non-zeros, then fill the rest with 0).

A neat variation allows at most two copies of each value: keep a[r] when w is less than 2 or a[r] differs from a[w - 2].

Three pointers solve the Dutch national flag problem, sorting an array of 0s, 1s and 2s in one pass. low marks the end of the 0s, high the start of the 2s, and mid scans. A 0 swaps to low, a 2 swaps to high, and a 1 just moves on. It costs O(n) time and O(1) space.

  • Keep invariant: a[0..w-1] is the answer so far
  • Do not advance mid after swapping with high
  • In-place matters when the task says O(1) extra space

Fast and slow pointers

Floyd's cycle detection moves slow one node and fast two nodes per step on a linked list. If there is no cycle, fast reaches None. If there is one, both pointers end up inside it, and the gap between them shrinks by one each step, so they must meet. This uses O(n) time and O(1) space, where a visited set would need O(n) memory.

To find where the cycle starts, put one pointer back at the head after they meet, then move both one step at a time. They meet again exactly at the cycle's first node.

The same trick finds the middle of a list: when fast reaches the end, slow is in the middle. It even works on arrays where each value points to another index, as in finding the duplicate number in an array of n + 1 values from 1 to n.

CycleOne step of Floyd's loop
  1. 1
    slow = slow.next

    One step.

  2. 2
    fast = fast.next.next

    Two steps.

  3. 3
    fast is None?

    Yes: no cycle, stop.

  4. 4
    slow is fast?

    Yes: cycle found, stop.

  5. Back to step 1

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Use converging pointers on sorted arrays~45m
  2. 2
    Solve two-sum II and three-sum~45m
  3. 3
    Remove duplicates in place~45m
  4. 4
    Solve container with most water~45m

Key points

  • Converging pointers: O(n) time, O(1) space on sorted arrays.
  • Three-sum: sort, then fix one element and run two pointers, O(n^2).
  • Same-direction pointers remove duplicates in place in O(n).
  • Container with most water: always move the shorter side.

Key terms

Tap a card to flip it. 0/3 known

Examples

python
def two_sum_sorted(a, target):    # O(n), O(1) space
    left, right = 0, len(a) - 1
    while left < right:
        s = a[left] + a[right]
        if s == target: return left, right
        if s < target: left += 1
        else: right -= 1

def dedupe(a):                    # in place, returns new length
    w = 0
    for r in range(len(a)):
        if r == 0 or a[r] != a[r - 1]:
            a[w] = a[r]; w += 1
    return w

Three-sum on [-1, 0, 1, 2, -1, -4]

Step 1: sort to [-4, -1, -1, 0, 1, 2]. Step 2: i = 0 fixes -4, so we need a pair summing to 4, but the largest pair is 1 + 2 = 3, so nothing is found. Step 3: i = 1 fixes -1. left points at -1 and right at 2: the sum is 0, so record [-1, -1, 2]. Move both: left at 0, right at 1, sum 0, record [-1, 0, 1]. Step 4: i = 2 is another -1, so skip it. Step 5: i = 3 fixes 0; 1 + 2 is too big and the pointers cross. Result: two triplets.

python
def three_sum(a):                 # O(n^2) time
    a.sort(); out = []
    for i in range(len(a) - 2):
        if i > 0 and a[i] == a[i - 1]: continue
        l, r = i + 1, len(a) - 1
        while l < r:
            s = a[i] + a[l] + a[r]
            if s < 0: l += 1
            elif s > 0: r -= 1
            else:
                out.append([a[i], a[l], a[r]])
                l += 1; r -= 1
                while l < r and a[l] == a[l - 1]: l += 1
    return out

Container with most water on [1, 8, 6, 2, 5, 4, 8, 3, 7]

Step 1: left = 0 (height 1), right = 8 (height 7). Area = min(1, 7) * 8 = 8. The left wall is shorter, so move it. Step 2: left = 1 (height 8), right = 8 (height 7). Area = 7 * 7 = 49. Now the right wall is shorter, so move right. Step 3: right = 7 (height 3) gives 3 * 6 = 18, still worse. The loop continues until the pointers meet, and no later pair beats 49. Nine heights, eight area checks, instead of 36 pairs.

python
def max_area(h):                  # O(n) time, O(1) space
    l, r, best = 0, len(h) - 1, 0
    while l < r:
        best = max(best, min(h[l], h[r]) * (r - l))
        if h[l] < h[r]: l += 1
        else: r -= 1
    return best

print(max_area([1, 8, 6, 2, 5, 4, 8, 3, 7]))   # 49

Quick reference

  • Converging pointers need sorted input (or another monotonic rule) to know which side to move
  • Pair sum: sorted plus two pointers is O(n) time, O(1) space; a hash set is O(n) time and O(n) space
  • Three-sum: sort, fix i, two pointers on the rest; O(n^2); skip equal a[i] and equal a[l] after a hit
  • Container with most water: area = min(h[l], h[r]) * (r - l); always move the shorter wall
  • Read/write pointers: if a[r] is kept, write it to a[w] and do w += 1; w is the new length
  • At most two copies in a sorted array: keep a[r] when w < 2 or a[r] != a[w - 2]
  • Floyd: slow moves 1, fast moves 2; they meet only if there is a cycle; O(n) time, O(1) space
  • Dutch national flag (0s, 1s, 2s): low, mid and high pointers, one pass, O(1) extra space

Common mistakes

  • Applying converging pointers to unsorted input.
  • Skipping duplicate handling in three-sum, producing repeated triplets.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1In two-sum on a sorted array, a[left] + a[right] is smaller than the target. What do you do?

Question 2

2What is the time complexity of three-sum with sorting and two pointers?

Question 3

3In container with most water, why is it safe to move the shorter wall?

Question 4

4How much extra memory does Floyd's cycle detection use?

Question 5

5Which task is a poor fit for converging pointers on the raw input?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Move all zeros in a list to the end, in place, keeping the order of the other numbers. Example: [0, 1, 0, 3, 12] becomes [1, 3, 12, 0, 0].

  2. Exercise 2medium

    Given a sorted list, remove duplicates in place so each value appears at most twice. Return the new length. Example: [1, 1, 1, 2, 2, 3] gives 5 and starts with [1, 1, 2, 2, 3].

  3. Exercise 3hard

    Trapping rain water: given bar heights, return how much water is trapped after rain, in O(n) time and O(1) space. [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] gives 6.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Does the array have to be sorted for two pointers?
Only for the converging pattern that compares sums. Same-direction pointers (filtering, removing duplicates) and fast and slow pointers work on unsorted data.
When should I use a hash map instead of two pointers?
Use a hash map when the input is unsorted and you need original indexes, as in the classic two-sum. Use two pointers when the data is sorted or you need O(1) extra space.
What is the difference between two pointers and sliding window?
A sliding window is a same-direction two-pointer pattern where everything between the pointers matters, such as a sum or a character count. In plain two pointers, usually only the two pointed-at elements matter.

Go deeper

ShareXLinkedInWhatsApp