AlgoTales · Roadmap

Two pointers

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Two pointers means keeping two markers on a list and moving them toward each other or in the same direction, so you check each item only once. It often replaces a slow double loop with a single pass.

Practical use cases

  • Web app: Two items that exactly use a gift card. A shop sorts products by price and a user has a 1,000 rupee voucher. One marker starts at the cheapest item, the other at the dearest; if the sum is too high move the right marker down, too low move the left up. The pair is found in one pass instead of trying every pair, so the suggestion appears while the user is still on the page.
  • Web app: Removing duplicates from a sorted import. A CSV of sorted email addresses has repeats. One pointer reads, one writes the next unique value, so the cleaned list is built in place in a single pass. The cleaned list is made in place with no extra memory, so even a long import finishes quickly.
  • Web app: Merging two sorted lists on a feed. A news page merges two already-sorted lists of posts by date. One marker per list, always taking the newer item, gives a sorted combined feed quickly. Each list is walked once, so a feed made from 10,000 posts is ready in one quick pass.
  • System: Palindrome and sorted-data checks. Text tools check palindromes by comparing letters from both ends inward, and database engines merge sorted results the same way. Each item is visited at most once, which keeps these tools fast on large inputs.

The story: The Two Ends of the Mohalla Wall

Mrs. Sharma stood Mira and Kabir at the two ends of a long compound wall that had pillars of different heights. "Put a tarpaulin between two pillars to make a rain tank," she said. "The tank is as wide as the distance between you, but the water spills over the shorter pillar. Find the pair that holds the most water."

Kabir started the slow way: pillar 1 with pillar 2, pillar 1 with pillar 3, pillar 1 with pillar 4... by pillar 40 his hand was tired. There are so many pairs! Mira said, "Why not start at the two ends, where the tank is widest, and walk inward?"

Here was her trick. At the ends, the shorter pillar is the bottleneck. If you keep the short one and move the tall one inward, the tank only gets narrower and the short pillar still caps the water, so it can never improve. So drop the short pillar and step that side inward, hoping for something taller. Two walkers, one pass, no pair-by-pair checking.

That is the two pointers pattern. Learn its smell: the problem talks about a pair or a sorted line, and wants you to avoid checking every pair.

How to spot this problem, and where you need it

You are checking pairs in a list with a loop inside a loop, but the list is sorted or has a structure that tells you which side to move.

Signs you need it

  • The task is about pairs or triples with a target sum, or comparing from both ends, or removing duplicates in place.
  • The data is sorted, or can be sorted cheaply first.
  • You have two nested for-loops that both run over the same array.

Where to use it in a project

  • Price matchers, voucher finders and budget pair finders on shopping pages.
  • Data cleaning of sorted lists, such as removing repeated emails from an import.
  • Merging two sorted result sets or feeds into one sorted list.

The solution

Place one pointer at each end (or both at the start). Look at the two items. If the sum is too big, the right one is too big for any partner, so move it inward; if too small, move the left one. Each step discards one item for good, so after at most one pass through the list you have either found the answer or proven there is none.

Payoff: Before: 10,000 items means 50 million pair checks. After: at most 10,000 steps.

Explain it like I am 8

Two friends stand at both ends of a skipping rope lying on the ground. Each time, the friend holding the lower end walks inward to look for a better spot. They meet in the middle and you have checked a whole playground without trying every pair.

How it works, step by step

  1. Clue: "pair", "two ends", "sorted", "palindrome", "in place". When you see these, think two pointers.
  2. Place one pointer at each end (l = 0, r = n - 1) so you start with the widest choice.
  3. Score the current pair and remember the best score.
  4. Decide who must move. Move the pointer whose side is the bottleneck (here, the shorter wall). Throwing it away cannot lose the answer.
  5. Stop when the pointers meet. Each step discards a whole group of pairs, so you finish in one pass.

The code in four languages

PHP

<?php
// Container With Most Water: two pointers start at the two ends
function maxWater(array $h): int {
    $l = 0;
    $r = count($h) - 1;
    $best = 0;
    while ($l < $r) {
        $area = min($h[$l], $h[$r]) * ($r - $l);   // width x shorter wall
        $best = max($best, $area);
        if ($h[$l] < $h[$r]) {
            $l++;          // left is the bottleneck, drop it
        } else {
            $r--;          // right is the bottleneck (or equal), drop it
        }
    }
    return $best;
}
echo maxWater([1, 8, 6, 2, 5, 4, 8, 3, 7]);   // 49

JavaScript

// Container With Most Water: two pointers start at the two ends
function maxWater(h) {
  let l = 0;
  let r = h.length - 1;
  let best = 0;
  while (l < r) {
    const area = Math.min(h[l], h[r]) * (r - l);   // width x shorter wall
    best = Math.max(best, area);
    if (h[l] < h[r]) {
      l++;          // left is the bottleneck, drop it
    } else {
      r--;          // right is the bottleneck (or equal), drop it
    }
  }
  return best;
}
console.log(maxWater([1, 8, 6, 2, 5, 4, 8, 3, 7]));   // 49

Java

public class Main {
    // Container With Most Water: two pointers start at the two ends
    static int maxWater(int[] h) {
        int l = 0;
        int r = h.length - 1;
        int best = 0;
        while (l < r) {
            int area = Math.min(h[l], h[r]) * (r - l);   // width x shorter wall
            best = Math.max(best, area);
            if (h[l] < h[r]) {
                l++;          // left is the bottleneck, drop it
            } else {
                r--;          // right is the bottleneck (or equal), drop it
            }
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(maxWater(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7}));   // 49
    }
}

Go

package main

import "fmt"

// maxWater solves Container With Most Water: two pointers start at the two ends.
func maxWater(h []int) int {
	l, r := 0, len(h)-1
	best := 0
	for l < r {
		area := min(h[l], h[r]) * (r - l) // width x shorter wall
		best = max(best, area)
		if h[l] < h[r] {
			l++ // left is the bottleneck, drop it
		} else {
			r-- // right is the bottleneck (or equal), drop it
		}
	}
	return best
}

func main() {
	fmt.Println(maxWater([]int{1, 8, 6, 2, 5, 4, 8, 3, 7})) // 49
}

Time: O(n) · Extra space: O(1). Every step moves one pointer inward, so at most n steps; checking all pairs would be O(n²).

Watch out for

  • Moving the taller wall. That keeps the short wall as the cap while the width shrinks, so you can only lose.
  • Using two pointers on unsorted data when the move rule depends on order (like pair-sum). Sort first, or use hashing.
  • Looping with l <= r and pairing a wall with itself.

Quick check

  1. Which clue most strongly suggests two pointers?
    • Needing the k-th smallest value
    • A tree with many children
    • A sorted array and a pair to find
  2. In the water problem, which pointer moves?
    • The one on the taller wall
    • The one on the shorter wall
    • Always the left one
  3. What is the running time?
    • O(n²)
    • O(log n)
    • O(n)