DEV Community

Cover image for Two pointers technique for coding interviews, explained
Gowtham Potureddi
Gowtham Potureddi

Posted on

Two pointers technique for coding interviews, explained

Two pointers technique for coding interviews, explained

The two pointers technique is one of the first patterns worth making automatic for a coding interview, because two indices walking an array or list replace a whole nested loop and turn an O(n²) brute force into a clean O(n) pass with no extra memory. The pattern: instead of comparing every element with every other, you place two pointers and move them with intent — toward each other from the ends of a sorted array, or in the same direction at different speeds — so the structure of the data does the work the second loop used to do.

It is worth learning as a pattern because the three shapes it takes cover an enormous range of problems, and recognising which shape a problem needs is most of the battle. This guide covers the core idea, the three templates — converging pointers from both ends, same-direction read/write pointers, and fast-and-slow pointers for linked lists — the signals that tell you to reach for it, the problems it solves, and the follow-ups an interviewer uses to check you understand why moving a pointer is safe, not just that it works.

Title card for a coding interview explainer on the two pointers technique, showing two indices converging from both ends of a sorted array and a fast and slow pointer on a linked list, collapsing a nested loop into an O(n) pass, on a dark citrus-and-lavender background.

Why two pointers comes up in coding interviews

Interviewers reach for two-pointer problems because the brute force is a comfortable nested loop and the efficient answer requires an insight about why you can skip work. You are asked to find a pair in a sorted array that sums to a target, you write two loops, and the interviewer asks the question that is the real point: the array is sorted — can you use that to do it in one pass and no extra space? That is the moment the technique earns its place, and the moment a candidate who only memorised solutions, rather than the idea, gets stuck justifying why the move is correct.

The interviewer rarely lets the nested loop stand. "It's sorted — that's O(n squared) and O(n) extra space with a hash set. Do it in one pass with no extra memory, and tell me why moving the pointer never skips the answer." That question — the correctness of the move, not just its speed — is the one a memorised solution can never survive, and the one this pattern is really testing.

The rounds on Zynter are modelled on how the loop runs, not scraped from any candidate's recall. What matters for prep is the shape: you give a solution, and the next sentence out of the interviewer's mouth asks you to make it faster, use less space, or justify why a pointer can move.

What the interviewer is really testing

A coding answer is read on four dimensions, and two pointers exercises all of them. Problem solving — did you notice the sorted input or the in-place requirement and reach for pointers instead of a hash set? Communication — can you say in one sentence why moving the left pointer up (because the sum was too small) can never skip a valid pair? Technical execution — can you write the template cleanly and handle the pointer-crossing termination? Time management — did you get to O(n) and O(1) space without an off-by-one bug? Reading this guide teaches the pattern; it does not teach you to narrate the pointers while someone asks why the move is safe.

Shape one: converging pointers on a sorted array

The classic shape. On a sorted array, put one pointer at each end and move them toward each other based on how the current pair compares to the target. For "find a pair that sums to target":

def pair_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        # need a bigger sum -> move left up
        else:
            right -= 1       # need a smaller sum -> move right down
    return None
Enter fullscreen mode Exit fullscreen mode

The insight to say out loud is why the move never misses the answer: because the array is sorted, if the sum is too small the only way to increase it is to move left up — the current left cannot pair with anything smaller than right to reach the target, so discarding it loses nothing. Each step eliminates one element, so the whole scan is O(n) with O(1) space — strictly better than the hash-set approach on memory. This shape also powers three-sum (fix one element, two-pointer the rest), container-with-most-water, and valid-palindrome checks.

A diagram of converging two pointers on a sorted array showing a left pointer at the start and a right pointer at the end, with the rule that if the pair sum is too small the left pointer moves up and if it is too large the right pointer moves down, so each step eliminates one element for an O(n) scan with O(1) space.

Shape two: same-direction and fast-and-slow pointers

The other two shapes move both pointers the same way, at a fixed or a varying gap.

Same-direction read/write (in-place). For modifying an array in place — removing duplicates from a sorted array, moving zeros to the end — a slow write pointer marks where the next kept element goes while a fast read pointer scans ahead. The slow pointer only advances when the fast pointer finds something worth keeping:

def remove_duplicates(nums):
    write = 0
    for read in range(len(nums)):
        if read == 0 or nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1
    return write      # length of the de-duplicated prefix
Enter fullscreen mode Exit fullscreen mode

Fast-and-slow (Floyd's) on a linked list. Two pointers moving at different speeds — fast two steps, slow one — detect a cycle (if they ever meet, there is a loop), find the middle of a list (when fast reaches the end, slow is at the middle), and find the start of a cycle. The varying gap is the trick: in a cycle the fast pointer laps the slow one and they collide; on a straight list the fast pointer simply reaches the end.

The rule to say: converging pointers for a sorted array and a pair/triplet condition; same-direction read/write for in-place array work; fast-and-slow for linked-list cycle and middle. Naming which of the three a problem needs is the recognition the round is testing.

A diagram showing two same-direction two-pointer shapes: a slow write pointer and a fast read pointer compacting an array in place by only advancing the write pointer on a kept element, and a fast pointer moving two steps while a slow pointer moves one on a linked list to detect a cycle when they meet or find the middle when the fast pointer reaches the end.

Coding
Coding · Arrays & linked lists
Solve a two-pointer problem out loud

Practise on Zynter →

How to recognise a two-pointer problem

The pattern lives behind a small set of signals. When a prompt has these shapes, reach for two pointers before a nested loop or a hash set:

The prompt says… Reach for…
"sorted array" + "pair / triplet summing to X" converging pointers from both ends
"is it a palindrome" / "reverse in place" converging pointers
"remove duplicates / move zeros in place, O(1) space" same-direction read/write pointers
"linked list" + "cycle / middle / nth from end" fast-and-slow pointers
"container with most water" / "trapping rain water" converging pointers with a width calculation

The two signals that matter most are sorted input (which makes converging pointers safe) and an in-place / O(1)-space requirement (which rules out the hash set). If the array is unsorted and you need a pair sum, a hash map is usually better than sorting just to two-pointer it — reaching for pointers on unsorted data is the common mistake. Say the recognition out loud: "it's sorted and asks for a pair, so converging two pointers, O(n) and O(1) space."

A recognition cheat sheet for the two pointers technique mapping prompt phrases to the right shape, showing a sorted array pair sum mapping to converging pointers, in-place removal with O(1) space mapping to same-direction read-write pointers, and a linked-list cycle or middle mapping to fast-and-slow pointers, with a warning that an unsorted pair-sum is usually a hash map instead.

Problems the two-pointer pattern solves

These are the canonical problems; practise them until the shape is reflex, not memory:

  • Two sum II (sorted input) — converging pointers; move based on the sum versus target.
  • Three sum — sort, fix one element, converging two-pointer the remainder; skip duplicates.
  • Valid palindrome — converging pointers from both ends comparing characters.
  • Container with most water — converging pointers; move the shorter wall inward.
  • Remove duplicates / move zeroes — same-direction read/write pointers, O(1) space.
  • Linked list cycle, middle node, nth from end — fast-and-slow pointers at different speeds.

Each is one of the three shapes with a different move rule. Once you have solved two or three out loud per shape, the next one is recognition plus the template — exactly the muscle a timed round tests.

Coding
Coding · Linked list cycle
Narrate fast-and-slow pointers out loud

Practise on Zynter →

The follow-ups that decide a two-pointer question

The probes rhyme across every two-pointer problem. Master these and you can defend the pattern in any version of the question.

  • "It's sorted — can you avoid the hash set?" → Yes: converging pointers, O(n) time and O(1) space, because sorting lets the sum guide which pointer to move. (problem solving)
  • "Why does moving the left pointer never skip a valid pair?" → Because the sum was too small and the current left cannot reach the target with any smaller right, so discarding it loses nothing. (communication)
  • "Remove duplicates with no extra array — how?" → A slow write pointer and a fast read pointer; the write pointer only advances on a kept element. (technical execution)
  • "Detect a cycle in a linked list in O(1) space." → Fast-and-slow pointers; if fast ever meets slow there is a cycle, otherwise fast reaches the end. (technical execution)
  • "What are the time and space complexities, and the termination condition?" → O(n) time, O(1) space; the loop ends when the pointers cross (left < right) or fast reaches the end. (problem solving)

Each maps to a debrief dimension. Reading them teaches the answers; it does not teach you to deliver them while someone interrupts with "prove the move is safe" — that only comes from saying them out loud.

How to prepare: a short plan

You do not need a hundred problems. You need the three shapes automatic and the recognition instant, so a sorted-pair or in-place or linked-list prompt triggers the right pointers without thinking.

  • Day 1: Learn the three shapes and write each template from memory — converging on a sorted array, same-direction read/write, and fast-and-slow on a list — and be able to say why each move is safe.
  • Day 2: Drill recognition on ten prompts: for each, say "which shape, and why" (sorted? in-place? linked list?) before writing a line. This is the skill the round tests.
  • Day 3: Solve two problems per shape out loud, timed, narrating the pointers and answering "why is the move correct" as you go, with someone (or something) pushing for the O(1)-space version.

This pattern is one row of the broader coding interview patterns — once two pointers and the sliding window are automatic, most array and linked-list questions become recognition plus a template.

Frequently asked questions

What is the two pointers technique?

The two pointers technique uses two indices moving over an array or linked list to replace a nested loop, usually cutting an O(n²) brute force to O(n) with O(1) extra space. It takes three main shapes: converging pointers that start at both ends of a sorted array and move toward each other based on a condition, same-direction read and write pointers that compact or modify an array in place, and fast-and-slow pointers that move at different speeds to find cycles or the middle of a linked list. The common idea is that the structure of the data — sortedness, or the geometry of a cycle — lets you move a pointer with confidence instead of re-scanning.

When should I use two pointers in an interview?

Reach for two pointers when the input is a sorted array and you need a pair or triplet matching a condition, when you must modify an array in place with O(1) extra space, or when a linked-list problem asks for a cycle, the middle node, or the nth node from the end. The two strongest signals are a sorted input, which makes converging pointers provably safe, and an in-place or constant-space requirement, which rules out a hash set. If the array is unsorted and you just need a pair sum, a hash map is usually the better tool than sorting purely to apply two pointers.

What is the difference between two pointers and a sliding window?

A sliding window is a specific two-pointer pattern where both pointers move in the same direction and define a contiguous range that grows and shrinks, used for contiguous subarray and substring problems. The broader two-pointer technique also includes converging pointers that move toward each other from both ends of a sorted array for pair and triplet problems, and fast-and-slow pointers that move at different speeds on a linked list for cycle detection. So the sliding window is one branch of the two-pointer family, specialised for maintaining a contiguous window, while two pointers covers converging and fast-slow movement as well.

Why can converging pointers skip elements safely?

On a sorted array, when the pair at the two pointers sums to less than the target, the element at the left pointer cannot form a valid pair with anything to the left of the right pointer, because those values are all smaller and would make the sum even smaller. So moving the left pointer up discards an element that provably cannot be part of the answer, which is why it is safe. The symmetric argument holds when the sum is too large and you move the right pointer down. This "each move eliminates an element that cannot help" argument is exactly what the interviewer wants you to state.

What is Floyd's fast-and-slow pointer algorithm?

Floyd's algorithm uses two pointers on a linked list that move at different speeds — the fast pointer advances two nodes for every one the slow pointer takes. If the list has a cycle, the fast pointer eventually laps the slow pointer and they meet, which detects the loop in O(1) extra space; if the list is straight, the fast pointer reaches the end. The same idea finds the middle of a list — when the fast pointer reaches the end, the slow pointer is at the middle — and, with a second phase, the start node of a cycle. It is the standard answer for linked-list cycle and middle problems.

How do I practise coding interviews out loud?

Reading about two pointers is not the same as narrating one while an interviewer asks you to prove the move is safe. On Zynter, the Coding track runs live voice rounds modelled on how real coding loops run — you solve in a real editor where your code runs, and a voice interviewer pushes with the follow-ups above one at a time ("it's sorted — avoid the hash set?", "why does moving the pointer never skip a pair?"), then gives you a debrief on problem solving, communication, technical execution and time management. The score is a practice signal, not a hiring decision.

Practise it on Zynter

You can recite the templates. The round is won on proving the pointer move is safe, out loud.

Pick a Coding round, solve a two-pointer problem in a real editor, and defend it out loud to a voice interviewer that keeps asking "it's sorted — can you avoid the hash set?" and "why does moving the pointer never skip the answer?" — then read the debrief. Zynter.ai is on-demand mock interviews modelled on real company loops, with 150+ rounds across 20 companies including the Coding track (Sep 2026).

Practise a Coding round →
Browse all interview tracks

Top comments (0)