← Blog

Two Pointers Technique: When to Use It and Spot It

By the DevInterview TeamPublished July 18, 2026

The two pointers technique uses two indices moving through a data structure to replace a nested loop, turning an O(n²) brute force into a single O(n) or O(n log n) pass. Reach for it when you have a sorted (or sortable) array, a linked list, or a string, and you are searching for a pair, a window, or a partition. The tell is almost always the same: your first instinct is a double loop where the inner loop re-scans data the outer loop already touched. That redundant re-scanning is exactly what two pointers eliminates.

We run mock interviews all day, and this pattern is one of the highest-leverage things a mid-level candidate can drill. It shows up constantly, the optimal solutions are short, and interviewers use it to see whether you can move from brute force to optimal out loud. Below is how to recognize it and the variants worth knowing cold.

What the technique actually is

Two pointers means you maintain two positions into a sequence and advance them according to a rule, so that each element is visited a constant number of times. The pointers do not have to be two separate variables. As long as the second position is derived from the first (for example, i and i+1, or a read pointer and a write pointer), it counts as the same idea.

The reason it works is monotonicity. If the data has some ordering property, then moving a pointer in one direction can only increase or only decrease the quantity you care about. That lets you rule out large chunks of the search space without checking them. When there is no such ordering to exploit, two pointers usually does not apply, and you are looking at hashing, a heap, or dynamic programming instead.

A canonical example: given a sorted array, find two numbers that sum to a target. Brute force checks every pair in O(n²). With two pointers, start left at index 0 and right at the last index. If the sum is too small, move left right to increase it; if too big, move right left to decrease it. Each step eliminates a row or column of the pair matrix, so you finish in O(n).

def two_sum_sorted(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        s = nums[left] + nums[right]
        if s == target:
            return [left, right]
        if s < target:
            left += 1
        else:
            right -= 1
    return []

How to spot a two-pointers problem

You rarely get told to use two pointers. You infer it from the problem shape. Here are the triggers we tell candidates to watch for:

The meta-move in an interview is to state the brute force first, name the wasted work explicitly, and then propose two pointers as the fix. That narration is what interviewers score, not just the final code. If you want to rehearse that specific transition, our writeups on mastering arrays and hashing and the Meta question breakdown show how often the pattern recurs in real loops.

The four variants worth knowing

Converging pointers (opposite ends)

Both pointers start at the extremes and move toward each other. Use it for sorted pair-sum, palindrome validation, and area problems. Maximum Width Ramp is a good stretch case: you want the largest j - i with nums[i] <= nums[j]. A clean solution builds a monotonic candidate set of left indices, then sweeps j from the right, but the underlying instinct (find the widest valid pair) is pure two pointers thinking about the endpoints.

Fast and slow (same direction, different speeds)

One pointer moves faster than the other. This is the read/write compaction pattern (removing elements in place) and the cycle-detection pattern in linked lists. Swap Adjacent in LR String rewards this framing: because L only moves left and R only moves right, you walk two pointers across the source and target strings, skipping X, and check that each real character lines up with a legal relative position. No extra data structure needed.

Two pointers over two inputs

Keep one pointer per sequence and advance whichever is behind. The k Strongest Values in an Array fits neatly here: sort the array, compute the median, and then a pointer at each end picks the "strongest" values by comparing distance from the median, moving inward k times. Most Profit Assigning Work is the same idea across two sorted lists: sort jobs by difficulty and workers by ability, then sweep a job pointer forward as the worker pointer advances, tracking the best profit seen so far.

Anchored pointer plus a window

A fixed reference index with a moving companion. Find Indices With Index and Value Difference II asks for indices i and j at least indexDifference apart with a large enough value gap. You slide j forward while a lagging pointer tracks the running min and max value among indices that are far enough back, which is a two-pointer plus running-extremes combination. Shortest Unsorted Continuous Subarray uses two ends too: scan from the left to find where order breaks and from the right for the same, then reconcile the boundaries against the array's true min and max in that region.

Where two pointers is not the answer

Not every "pair" problem is two pointers. If the array is unsorted and sorting would lose the original indices you need to return, a hash map is usually better. If you need the maximum over many overlapping subarrays with an aggregate that does not move monotonically, prefix sums or a deque beat naive pointers.

Some problems look like two pointers but need more. Create Maximum Number combines a greedy subsequence pick with a merge step; the merge compares two candidate arrays lexicographically, which is pointer-driven, but the outer structure is greedy, not two pointers alone. Last Substring in Lexicographical Order is the sharpest trap: it reads like a two-pointer scan, and the optimal solution does use two candidate pointers i and j plus an offset k, but getting the pointer-advance rule right (when characters tie, extend k; when they differ, jump the losing pointer past the compared region) is subtle. Do not assume the obvious pointer motion is correct; prove the invariant.

How to talk about it in the interview

State complexity up front. Converging and fast/slow variants are O(n) time and O(1) extra space, which is a strong selling point to say out loud. If you sort first, say the total is O(n log n) dominated by the sort. Then name your invariant in one sentence: "left only moves right when the sum is too small, so I never skip a valid pair." Interviewers at companies like Google care more about that invariant than about tidy syntax, because it proves you understand why the shortcut is safe.

FAQ

When should I use two pointers instead of a hash map?

Use two pointers when the data is sorted or you can sort it, and when you want O(1) extra space. Use a hash map when the array is unsorted, you must preserve original indices, or you need O(1) average lookups more than you need to save memory. For the classic unsorted Two Sum that returns indices, a hash map wins; for the sorted version, two pointers wins.

Is the sliding window a two pointers technique?

Effectively yes. A sliding window is a two pointers variant where both indices move in the same direction and the region between them is your window. The distinction people draw is that sliding window tracks an aggregate over a contiguous range, while classic two pointers often compares elements at the two positions directly.

What time complexity does two pointers give me?

Most two pointer solutions run in O(n) time because each pointer traverses the sequence at most once. If a sort is required first, the total becomes O(n log n). Extra space is typically O(1), which is a big part of why interviewers like the pattern.

How do I practice spotting it quickly?

Solve 15 to 20 tagged problems in one sitting and, before coding each, write one line naming the trigger (sorted pair, both ends, fast/slow, two inputs). Pattern recognition is a muscle: after enough reps, you see the double loop and the pointer fix at the same time. Mixing easy and staff-level problems like Last Substring keeps you from pattern-matching too shallowly.

Sources

The real one is coming. Be ready for it.

Take a realistic AI-led mock interview with questions top companies actually ask, with live voice and real feedback.

Start a mock interview

Your first interview is free · no credit card required

Keep reading