Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Arrays & Two Pointers

Two Pointers

O(n) / O(1)

Walk two indices toward each other (or same-direction) so each step discards a whole branch of possibilities.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
UnlocksSliding WindowQuickselectDivide and Conquer (merge-sort counting)
0%
mastery
0/53 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Sorted input (or sorting is free): find a pair/triplet with a target sum or best value, in-place dedupe/partition, or palindrome check.

  1. 1Brute force

    Check all O(n2) pairs (O(n3) triplets).

  2. 2The observation

    Pairs that cannot be optimal are skipped without being examined: monotonicity lets one comparison discard a whole row/column of the pair matrix.

  3. 3Why it works

    Every pair outside [l, r] is already proven useless or counted, so each step safely discards one candidate.

Reach for it when

  • +The array is sorted (or you can sort it) and you want a pair/triplet hitting a target.
  • +You're shrinking a range from both ends — palindrome check, container/area, trapping water.
  • +In-place rearrange with O(1) extra space — dedupe a sorted array, move zeroes, Dutch-flag partition.

Not when

  • ×Contiguous subarray under a running constraint (sum, count, distinct)use Sliding window
  • ×Unsorted pair-sum, or sorting would lose the original indices you must returnuse Hash map, O(n)
  • ×Sum-window with negative values: moving a pointer doesn't change the sum monotonicallyuse Prefix sum + hash map
  • ×You need every pair/triplet/combination, not a count or the best oneuse Enumeration / backtracking
  • ×Finding one value against a fixed target, not a relation between two elementsuse Binary search

Intuition

A pointer is nothing scary — it's just an index, a number that says "I'm looking at this slot." Think of your finger resting on one box of an array. i = 0 means your finger is on the first box. Moving the pointer means sliding your finger: i = i + 1.

Read the full intuition

So why two fingers? Because with one finger you can only look at one spot, and to compare every pair you'd need a finger that loops while the other loops too — that's n×n work. With two fingers placed cleverly, each step lets you throw away a whole bunch of possibilities at once, so you finish in one sweep.

The classic setup: the array is sorted, one finger on the far left (smallest), one on the far right (largest). You're hunting for a pair that sums to a target.

Walk [1, 2, 4, 7, 11, 15], target 9:

  • L→1, R→15. Sum = 16. Too big. The only way to get smaller is to give up that huge 15 — so move R left. (Moving L would only make it bigger.)
  • L→1, R→11. Sum = 12. Still too big → R left again.
  • L→1, R→7. Sum = 8. Too small now. The only way up is to drop the tiny 1 → move L right.
  • L→2, R→7. Sum = 9. Found it.

Key idea

The magic: at every step one move is provably useless, so you never waste it. That's why two sorted pointers turn O(n²) into O(n).

The second flavour is same-direction pointers: a slow finger that marks "where the clean part ends" and a fast finger that scans ahead — used for in-place dedupe, moving zeroes, partitioning (Sort Colors).

Why it costs what it costs

Time O(n). each pointer moves at most n steps and never backtracks, so total moves ≤ 2n. (O(n log n) if you must sort first.)

Space O(1). two integer indices, no extra structure (sorting may add O(log n) stack).

Practice

Next · Foundation

Valid Palindrome

Opposite-end pointers compare mirrored positions; skipping non-alphanumerics is just pointer movement.

0/53 solved
  • Valid PalindromeFoundationFoundationMeta, AppleEasy
  • Two Sum II - Input Array Is SortedApply it · Move a pointer based on comparing a sum with a target.Apply itAmazon, AdobeMedium
  • 3SumOne change · Add an outer loop fixing one element; inner two-sum on the rest.One changeMeta, AmazonMedium
  • Container With Most WaterTwists · Objective is area, not a sum; which pointer to move needs a proof.TwistsAmazon, AdobeMedium
  • Remove Duplicates from Sorted ArrayBranches · Same-direction read/write pointers instead of opposite ends.BranchesAmazon, MicrosoftEasy
  • Sort ColorsBranches · Three pointers partition into three regions (Dutch national flag).BranchesMicrosoft, AmazonMedium
  • Boats to Save PeopleCombine · Greedy pairing decision driven by two pointers after sorting.CombineUber, AmazonMedium
  • Trapping Rain WaterAdvanced · Pointers carry running maxima from each side.AdvancedAmazon, GoogleHard
  • Number of Subsequences That Satisfy the Given Sum ConditionMastery checkMastery checkMedium
  • Concatenation of ArrayAmazonEasy
  • Move ZeroesMeta, AmazonEasy
  • Next PermutationGoogle, AdobeMedium

Pitfalls

Classic bugs

  • !Forgot to sort first: opposite-end logic is meaningless on unsorted data.
  • !JS arr.sort() sorts as strings ([1,10,2]); always pass (a,b)=>a-b.
  • !3Sum duplicates: after recording a hit, skip equal values on both pointers.
  • !Loop guard must be while l < r so the pointers never land on the same element.
  • !C++ arr.size() - 1 on an empty array underflows (unsigned); cast to int first.
  • !Container With Most Water: only moving the shorter side is safe, not either pointer.
  • !Assuming it always needs sorted input: read/write compaction (dedupe, move zeros) works on any order.

Looks like it, isn't

  • Reverse Pairs needs Divide and Conquer (merge-sort counting)
    Why
    Pairs i < j with a[i] > 2a[j] are counted across merge-sort halves (or with a BIT).
  • 132 Pattern needs Monotonic Stack
    Why
    Need the best middle candidate for each position; a decreasing stack scanned from the right tracks it. source ↗
  • Max Value of Equation needs Monotonic Deque
    Why
    Rewriting gives a window maximum of (y - x).
  • 4Sum II needs Hash Map / Hash Set Lookup
    Why
    Four separate arrays: hash all a+b sums, look up -(c+d) (meet in the middle with a hash map).
  • Two Sum needs Hash Map / Hash Set Lookup
    Why
    Array is unsorted and indices are needed; sorting would lose them, so use complement lookup. source ↗
  • Longest Consecutive Sequence needs Hash Map / Hash Set Lookup
    Why
    O(n) required: start runs only at x where x-1 is absent in a hash set.
  • Find Peak Element needs Binary Search
    Why
    No sortedness, but the local slope gives a monotone predicate for binary search.
  • Maximum of Absolute Value Expression needs Manhattan <-> Chebyshev Rotation
    Why
    Expand the absolute values into 4 sign patterns; each needs only a max and min of a linear form. source ↗
Go deepervariants and techniques · 12 combinations · interviewer follow-ups · resources

Variants and techniques

  • Hash Map / Hash Set LookupStore seen values (or counts, or first index) in a hash map so 'have I seen x / how many x' is O(1) expected.
  • Boyer-Moore Majority VoteKeep a candidate and a counter; pairing off different elements never removes a strict majority element, giving O(n) time and O(1) space.
  • Simulation & Matrix TraversalCarry out exactly what the statement describes with careful index bookkeeping (layers, directions, in-place swaps).
  • Opposite ends (converging)L at start, R at end, move the one that improves your objective. Two Sum II, Container With Most Water, Valid Palindrome.
  • Fast & slow, same directionslow marks the boundary of the processed region, fast scans ahead; write to slow only when a condition holds. Remove duplicates, Move Zeroes.
  • Three pointers / Dutch flagFix the outer element with a loop, two-point the rest (3Sum), or keep low/mid/high to partition into three buckets (Sort Colors).
  • Two arraysOne pointer per array, advance the one pointing at the smaller value — merge step, intersection of sorted arrays.

Combinations

  • Prefix Sum+Hash Map / Hash Set Lookup

    count/longest subarrays with sum (or mod, or balance) equal to a target, negatives allowed

    Prefix Sum:
    turns every subarray into a pair of prefixes
    Hash Map / Hash Set Lookup:
    counts earlier prefixes with the needed value in O(1)

    Subarray Sum Equals KContiguous ArraySubarray Sums Divisible by K

  • Sliding Window+Hash Map / Hash Set Lookup

    longest/shortest substring with distinct/at-most-K/covers-all-chars condition

    Sliding Window:
    maintains a valid contiguous window
    Hash Map / Hash Set Lookup:
    keeps character/value frequencies for the validity test

    Longest Substring Without Repeating CharactersMinimum Window SubstringPermutation in String

  • Binary Search on the Answer+Two Pointers

    k-th smallest pair distance / k-th in a sorted matrix

    Binary Search on the Answer:
    searches the k-th value
    Two Pointers:
    counts how many pairs/cells are <= mid in linear time

    Find K-th Smallest Pair DistanceKth Smallest Element in a Sorted Matrix

  • Greedy+Two Pointers

    pair people/items under a capacity with minimum groups

    Greedy:
    pairing rule justified by exchange
    Two Pointers:
    realises the pairing on a sorted array

    Boats to Save PeopleFerris WheelApartments

  • Tree DFS (Paths & Recursion)+Prefix Sum+Hash Map / Hash Set Lookup

    count downward paths with a given sum

    Tree DFS (Paths & Recursion):
    walks root-to-node paths
    Prefix Sum:
    path sums as prefix differences
    Hash Map / Hash Set Lookup:
    counts prefix values on the current path

    Path Sum III

  • Mo's Algorithm (offline range queries)+Prefix Sum+Hash Map / Hash Set Lookup

    count subarrays in [l, r] with a pair property, many offline queries

    Mo's Algorithm (offline range queries):
    moves the query window
    Prefix Sum:
    subarray XOR as prefix XOR pair
    Hash Map / Hash Set Lookup:
    frequency counts of prefix values in the window

    XOR and Favorite Number

  • Hash Map / Hash Set Lookup+System / DS Design

    LRU/LFU caches

    Hash Map / Hash Set Lookup:
    maps each key to its list node in O(1)
    System / DS Design:
    a doubly linked list spliced in O(1) keeps recency order (LFU: one list per frequency)

    LRU CacheLFU Cache

  • Prefix Sum+Bit Tricks & Bitmasking+Hash Map / Hash Set Lookup

    substrings/subarrays where every letter (or bit) occurs an even number of times, or at most one is odd

    Prefix Sum:
    a substring's parity is prefix[j] ^ prefix[i]
    Bit Tricks & Bitmasking:
    a parity mask of the character counts replaces a count vector
    Hash Map / Hash Set Lookup:
    first index (or count) of each mask seen so far

    Find the Longest Substring Containing Vowels in Even CountsNumber of Wonderful SubstringsCount the Number of Beautiful Subarrays

  • Few Distinct Subarray OR / AND / GCD Values+Hash Map / Hash Set Lookup

    distinct subarray ORs, or the number of subarrays with AND equal to k

    Few Distinct Subarray OR / AND / GCD Values:
    at most log V distinct OR/AND values end at each index
    Hash Map / Hash Set Lookup:
    collect the distinct values, or count those equal to k

    Bitwise ORs of SubarraysNumber of Subarrays With AND Value of K

  • Few Distinct Subarray OR / AND / GCD Values+GCD / LCM & Euclid+Hash Map / Hash Set Lookup

    the number of subarrays whose gcd equals x, for many x

    Few Distinct Subarray OR / AND / GCD Values:
    O(log V) (gcd, count) pairs per right end
    GCD / LCM & Euclid:
    the gcd as j moves left only drops to a divisor
    Hash Map / Hash Set Lookup:
    global count of subarrays per gcd value

    CGCDSSQNumber of Subarrays With GCD Equal to K

  • Randomised Set Hashing (XOR / sum hashing, Zobrist)+Prefix Sum+Two Pointers

    subarrays that are permutations, or where every value occurs exactly k times

    Randomised Set Hashing (XOR / sum hashing, Zobrist):
    random labels make set identity additive
    Prefix Sum:
    a subarray's hash is a prefix difference/XOR
    Two Pointers:
    keep the window where no value exceeds k occurrences (1418G)

    The Number of SubpermutationsThree Occurrences

  • Mo's Algorithm (offline range queries)+Euler Tour / Tree Flattening+Hash Map / Hash Set Lookup

    many offline path queries counting pairs/distinct values on tree paths

    Mo's Algorithm (offline range queries):
    path = range with odd-toggle membership plus the LCA
    Euler Tour / Tree Flattening:
    a 2n entry/exit sequence
    Hash Map / Hash Set Lookup:
    frequency counts by value or gender pair

    Dating

Follow-ups interviewers ask

  1. 01What if the array isn't sorted? → sort first (O(n log n)) or use a hash map (O(n)) — discuss the tradeoff.
  2. 02What about 4Sum / k-Sum? → recurse: fix one more index and two-point the innermost, generalising the anchor loop.
  3. 03Return all pairs/triplets vs just one? → keep scanning and skip duplicates on both pointers.
  4. 04What if you can't modify the input (in-place dedup)? → copy first, or track a write index without overwriting until safe.

State table

step l r arr[l]+arr[r] vs target 9 action
1 0 5 1+15 = 16 too big r--
2 0 4 1+11 = 12 too big r--
3 0 3 1+7 = 8 too small l++
4 1 3 2+7 = 9 match ✓

Resources

  • Two PointersUSACO Guide · course
  • Prefix SumsUSACO Guide · course
  • More on Prefix Sums (difference arrays)USACO Guide · course
  • Array cheatsheetTech Interview Handbook · article
  • NeetCode RoadmapNeetCode · sheet
  • Array and String explore cardLeetCode · course
Sliding Window
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial