Patterns / Pattern 2 of 5
Two pointers
Walk through a list from both ends (or at two speeds) at once.
The 30-second version
To check whether a word reads the same backwards, you put one finger on the first letter and one on the last. You compare them, then move both fingers one step inward. Your fingers never go back, so you finish in a single sweep.
Two pointers, in three steps:
- Put one finger at the start and one at the end.
- Compare what the two fingers point at.
- Move a finger inward and repeat until they meet.
Think of it when a problem says:
- “the list is sorted”
- “reads the same backwards”
- “a pair in a sorted list”
- “change the list in place”
That’s the whole idea. The rest of this page shows it working, step by step.
Spot it when: The list is sorted, or you compare items from the start and the end.
In one line: Two fingers, each move rules something out for good.
Words on this page, in plain English (21)Open if any word is new to you
- Variable
- A labelled box that holds a value. You give it a name, put something in it, and use the name later to get it back.
- Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
- Index (position)
- Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.
- Length
- How many items a list (or letters a string) has. The last position is always
length - 1. - If (a decision)
- Runs some code only when something is true. Like: if it's raining, take an umbrella.
- Loop
- Code that repeats. A
forloop repeats once per item or a set number of times; awhileloop repeats as long as something stays true. - Nested loop
- A loop inside another loop. For each item, the inner loop goes through everything again, which gets slow fast.
- Function
- A named, reusable recipe. You give it ingredients (inputs), it does its steps, and hands back a result.
- Return
- How a function hands back its answer. As soon as
returnruns, the function stops. - console.log
- Prints something so you can see it. The easiest way to find out what your code is really doing.
- Map
- A lookup table: it stores pairs of a key and a value, and finds any key instantly. Like a coat check: hand over a ticket, get your coat straight back.
- Hash, hashing
- A quick calculation that turns a key into a shelf number, so a Map can jump straight to it instead of searching.
- Pattern
- A trick that solves a whole family of problems. Learn the trick once, and you can solve problems you've never seen.
- Template
- The usual shape of a pattern's code. You fill in the parts that change for each problem.
- Brute force (the slow way)
- Trying every possibility, one by one. It's usually easy to write and correct, but slow on big inputs.
- O(1): constant time
- Takes the same time no matter how big the input is. Like opening a book at page 1.
- O(n): linear time
- The work grows in step with the input: twice the items, twice the work. One pass.
- O(n²): quadratic time
- Twice the items means four times the work. Usually a loop inside a loop. Fine for 100 items, painful for 100,000.
- Pointer
- A variable that holds a position in a list, like a finger resting on one item.
leftandrightare pointers. - Sorted
- In order, smallest to biggest (or A to Z). Many fast tricks only work on sorted lists.
- In place
- Changing the list you were given, instead of making a new one. Saves memory.
Two fingers on a list
Imagine checking whether a word reads the same backwards, like level. You'd probably put one finger on the first letter and one on the last, compare them, then move both fingers inward. That's the whole idea of two pointers: two positions in the same list, moving towards each other or in the same direction, each step ruling out part of the list for good.
A pointer here is just a variable holding a position, like left = 0 or right = list.length - 1.
Try it: two pointers meeting in the middle
const letters = ["l", "e", "v", "e", "l"];
let left = 0;
let right = letters.length - 1;
while (left < right) {
console.log(left, right, letters[left], letters[right]);
left++;
right--;
}Press Run to see the output. You can change the code first.
Watch it work: close in from both ends
sorted
- target =
- 16
- sum =
- –
The list is sorted. Put left on the smallest number and right on the biggest. We want two that add up to 16.
Why it's fast
The slow way to compare things in a list is usually two nested loops: every item against every other, O(n²). With two pointers, every step moves at least one pointer, and neither ever moves back. So the pointers make at most n moves between them: O(n) time, and only two variables of extra memory, O(1).
The catch: you need a reason why moving a pointer never skips the answer. That reason usually comes from the list being sorted, or from the problem being symmetric (like comparing a word with its reverse).
Race: how much work as the input grows?
Try every pair O(n²)1,000,000 steps · 10 ms
Two pointers O(n)1,000 steps · instant
Times assume a fast computer doing about 100 million simple steps a second.
Template 1: from both ends, towards the middle
function solve(list) { let left = 0; let right = list.length - 1; while (left < right) { // look at list[left] and list[right] // then move left forward, or right back, or both }}Use it for: palindromes, reversing in place, pairs in a sorted list, "the biggest area between two lines".
Template 2: a slow and a fast pointer, same direction
One pointer (read) looks at every item. The other (write) marks where the next item you want to keep should go.
function keepSome(list) { let write = 0; for (let read = 0; read < list.length; read++) { if (/* list[read] should be kept */) { list[write] = list[read]; write++; } } return list.slice(0, write);}Use it for: removing items in place, squashing repeats in a sorted list, moving all zeros to the end.
How the pointers decide
In a sorted list of prices, looking for two that add up to a target:
- If
prices[left] + prices[right]is too small, the only way to grow the sum is a bigger left price:left++. - If it's too big, shrink it with a smaller right price:
right--. - If it's just right, you're done.
Each decision throws away one item that can't be part of any answer. That "can't be part of any answer" is the reason the pattern is correct. When you design a two-pointer solution, always ask: why is it safe to move this pointer?
When to use it
Reach for two pointers when:
- the list is sorted, or sorting it first is allowed,
- you compare items from both ends (palindromes, reversing),
- you need to change a list in place with no extra memory,
- the problem asks for a pair (or triple) that meets a condition.
Hashing or two pointers?
Both can find pairs. A Map works on unsorted lists but uses O(n) memory. Two pointers need a sorted list but use O(1) memory. If the list is already sorted, two pointers are usually the neater answer.
Common mistakes
while (left <= right)vswhile (left < right). With<=, both pointers can land on the same item. For pairs, you usually want<.- Forgetting to move a pointer. If some branch of your loop moves neither pointer, the loop never ends.
- Using it on an unsorted list. "Too small, so move left" only makes sense when moving left really makes the value bigger.
Learn it by heart
Understanding a pattern is the first half. The second is being able to write it without looking. Learn the recipe as words first, then each template in four steps. Your results go into your reviews, which bring each one back just before you’d forget it.
The recipe, out loud
- Put
leftat the start andrightat the end (or both at the start, at two speeds). - Loop while
left < right. - Look at both items and decide which pointer can safely move.
- Every step moves a pointer and none moves back, so it's O(n).
From both ends, towards the middle
Use it for: Compare the start with the end: mirrors, sorted pairs, reversing.
Learn it by heart: From both ends, towards the middle
Read the 10 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function isSameBothWays(list) { let left = 0; let right = list.length - 1; while (left < right) { if (list[left] !== list[right]) return false; left++; right--; } return true;}Read and write, same direction
Use it for: Keep some items and drop others, in place.
Learn it by heart: Read and write, same direction
Read the 10 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function keepPositives(list) { let write = 0; for (let read = 0; read < list.length; read++) { if (list[read] > 0) { list[write] = list[read]; write++; } } return list.slice(0, write);}Practice problems
Easiest first. Each has hints and a full walkthrough.
| Solved | Problem | Difficulty |
|---|---|---|
| Mirror phrase | easy | |
| Flip in place | easy | |
| Pair in a sorted list | easy | |
| Squash repeats | easy | |
| Biggest tank | medium | |
| Three to zero | medium |
More patterns
- Sliding window
Keep a stretch of the list and slide it along instead of starting over.
- Binary search
Halve the search space with every guess.
- Stack
Keep the most recent unfinished thing on top, and finish it first.
- Hashing and counting
Remember what you have seen in a Map, so you never search for it twice.
New to coding? Start with the JavaScript basics, or browse every practice problem.