CodingPatterns8 min read

Two Pointers

Two pointers is the first pattern to reach for when a problem hands you a sorted array, a string you need to compare against itself, or a linked list you can only walk forward. Instead of checking every pair of positions, which costs O(n²), you move two indexes through the data so that each step rules out a whole group of candidates. Most two-pointer solutions run in O(n) time and O(1) extra space, and that space bound is often the follow-up the interviewer is waiting for.

This lesson is for software engineering and data candidates preparing for a live coding round, from early career to senior. It covers the three shapes the pattern takes, a worked example with code, and the questions you will be asked once your solution works. Code is in Python.

When the pattern fits

Look for these cues in the problem statement:

  • The input is sorted, or sorting it is cheap and allowed. Sorted order is what lets one comparison discard many pairs.

  • You are looking for a pair (or triple) that meets a condition, such as a target sum or a closest difference.

  • You must modify an array in place: remove items, compact values, partition around a pivot.

  • The structure is a linked list and you need its middle, its end, or to know whether it loops.

  • The answer is symmetric: palindromes, reversing, comparing a string from both ends.

If the data is unsorted and order matters to the answer, two pointers usually does not apply; a hash map often does (see Hash Maps and Prefix Sums).

Shape 1: pointers at opposite ends

Start one pointer at each end of a sorted array and move them toward each other. The classic use is finding a pair that sums to a target.

def pair_with_sum(sorted_nums, target):
    left, right = 0, len(sorted_nums) - 1
    while left < right:
        total = sorted_nums[left] + sorted_nums[right]
        if total == target:
            return left, right
        if total < target:
            left += 1
        else:
            right -= 1
    return None

The reason this is correct is worth saying out loud, because it is what the interviewer scores as problem solving rather than recall. If the sum is too small, then sorted_nums[left] paired with any element at or before right is also too small, since everything before right is no larger. So left can never be part of an answer and you discard it. The same argument in reverse discards right when the sum is too large. Every step removes one candidate for good, so the loop runs at most n times.

Trace it on [1, 3, 4, 6, 9] with target 13: 1 + 9 = 10 is too small, move left; 3 + 9 = 12, move left; 4 + 9 = 13, return (2, 4).

The same shape solves "find three numbers that sum to zero": sort the array, fix each element in turn, and run the pair search on the elements after it. That is O(n²) overall, which beats the O(n³) of three nested loops. Skip a fixed element that equals the previous one, and skip repeated values after a match, or you will report duplicate triples.

Shape 2: pointers moving the same direction

Here one pointer reads and the other writes. The reader scans every element; the writer marks where the next kept element goes. Everything before the writer is the finished part of the answer.

Removing duplicates from a sorted array in place:

def dedupe_sorted(nums):
    if not nums:
        return 0
    write = 1
    for read in range(1, len(nums)):
        if nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1
    return write  # nums[:write] holds the unique values

On [1, 1, 2, 3, 3] the writer stops at 3 and the array begins [1, 2, 3]. The invariant to state is: "nums[:write] is the deduplicated prefix of everything read so far." Stating an invariant like that, before you code, is the fastest way to convince an interviewer your loop is right and to catch your own off-by-one errors.

The same reader and writer shape moves all zeros to the end while keeping the order of the other values, partitions an array around a value, and merges two sorted arrays from the back when the first has room at its end.

Shape 3: fast and slow pointers on a linked list

A linked list gives you no indexes and no length, so two pointers moving at different speeds do the measuring.

Finding the middle. Move slow one step and fast two steps. When fast runs off the end, slow is in the middle.

def middle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow

For 1 -> 2 -> 3 -> 4 -> 5 this returns 3. For 1 -> 2 -> 3 -> 4 it returns 3, the second of the two middles. If the problem wants the first middle, say so and change the loop condition to fast.next and fast.next.next (after handling an empty list, since that version reads fast.next on None). Pointing out which middle you return is the kind of detail that scores on testing and edge cases.

Detecting a cycle. If the list loops, the fast pointer eventually laps the slow one.

def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False

Why must they meet? Once both pointers are inside the loop, each step closes the gap between them by exactly one node, so the gap reaches zero within one lap. That makes it O(n) time and O(1) space, against O(n) space for the obvious alternative of storing visited nodes in a set. Compare node identity (is), not values: two different nodes can hold the same value.

Worked example: squares of a sorted array

Prompt: "You are given an array sorted in non-decreasing order, which may contain negative numbers. Return the squares of each value, also sorted."

A good start is to state the obvious solution and its cost: square everything and sort, O(n log n). Then look for what the sort is wasting. The input is already sorted, so the largest squares can only come from the two ends: a large negative number on the left or a large positive one on the right. That is an opposite-ends problem, filled from the back.

def sorted_squares(nums):
    result = [0] * len(nums)
    left, right = 0, len(nums) - 1
    for write in range(len(nums) - 1, -1, -1):
        if abs(nums[left]) > abs(nums[right]):
            result[write] = nums[left] ** 2
            left += 1
        else:
            result[write] = nums[right] ** 2
            right -= 1
    return result

Dry run on [-4, -1, 0, 3, 10]:

  1. write 4: compare 4 and 10, place 100, move right.

  2. write 3: compare 4 and 3, place 16, move left.

  3. write 2: compare 1 and 3, place 9, move right.

  4. write 1: compare 1 and 0, place 1, move left.

  5. write 0: both pointers on 0, place 0.

Result: [0, 1, 9, 16, 100]. Then test the edges out loud: a single element, all negatives (the answer reverses the order), all positives (nothing moves from the left), and repeated values.

Two candidates can end with this same code and get different reports. The weaker one writes square-and-sort, and when the interviewer asks for O(n), switches to two pointers without saying why the largest square must sit at an end; asked to test, they rerun the given example. The stronger one states the O(n log n) baseline first, names the insight before typing (problem solving), writes one loop with one job per line (code quality), traces the given input (correctness), tests the single-element, all-negative and duplicate cases without being asked (testing and edge cases), and keeps talking throughout (communication). Those are the five dimensions a SmartIntervu coding report scores, and the second candidate gave evidence for every one.

Tip

When you are not sure which pointer to move, ask "which element can no longer be part of any answer?" Move that one. If you cannot name one, the problem may not be a two-pointer problem.

Follow-ups to expect

The AI interviewer lets you drive, then asks you to explain your approach and its complexity and to test your code. If you stall, hints come in three steps: a nudge ("the input is sorted; what does that let you skip?"), a direction ("try one pointer at each end"), then something close to the solution. The report counts each hint and scores the dimension it helped with on what you did on your own, so a nudge costs less than the near-solution step. Once the code works, expect these:

  • "What if the array is not sorted?" Either sort first and pay O(n log n), noting that sorting loses the original indexes (keep (value, index) pairs if you need them), or switch to a hash map for O(n) time and O(n) space. Name the trade-off rather than picking silently.

  • "Can you do it without extra memory?" Two pointers is usually the answer to this one. Say what your space use is before you are asked.

  • "What about duplicates?" Decide whether the problem wants all pairs, unique pairs, or any pair, and show where you skip repeats.

  • "Where does the cycle start?" After slow and fast meet, reset one pointer to the head and move both one step at a time; they meet at the start of the cycle. You do not need to prove it on the spot, but say that it follows from the distances traveled.

What changes with seniority

For an early-career candidate, a correct two-pointer solution with a clear trace is a strong result. At mid-level the interviewer expects you to reach it without a hint and to state the invariant and complexity unprompted. Senior candidates are expected to move quickly through this pattern and spend their time on the harder variant: duplicates, the three-element version, or the cycle-start follow-up.

Mistakes that cost points

  • Moving the wrong pointer. It usually comes from not having a reason for each move. Say the discard argument for each branch.

  • while left <= right when the pair must be two different elements. With <=, the loop can pair an element with itself.

  • Losing indexes after sorting. If the problem asks for original positions, sorting values alone gives the wrong answer.

  • Dereferencing fast.next.next without checking fast.next. With only while fast:, an odd-length list crashes when fast reaches the last node. Checking only fast.next fails the other way, on even lengths. The loop condition must check both.

  • Comparing linked list nodes by value. Equal values do not mean the same node.

Practice it

Drill for the next 15 minutes: write pair_with_sum, dedupe_sorted and has_cycle from memory, then trace each on an empty input, a one-element input and a case with duplicates. Say the invariant for each before writing a line.

Then take Two Sum as a live interview. It is the unsorted version, so the strongest answer explains why two pointers would need a sort first and why a hash map wins here. Next in this series: Sliding Window.

Practise this in a mock interview

Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.

Read next

  • Sliding Window

    Spot contiguous-range problems, run fixed and variable windows from one template, decide where to record the answer, and explain why the window breaks once values can be negative.

    8 min read

  • Binary Search

    Write one boundary-search template without off-by-one bugs, derive exact, first, last and count searches from it, and binary search on the answer and on rotated arrays.

    9 min read

  • Hash Maps and Prefix Sums

    Use maps for lookup, counting and grouping, build prefix sums for constant-time range queries, and count or find target-sum subarrays with a map of earlier prefixes, negatives included.

    8 min read

  • Stacks and Monotonic Stacks

    Solve nested-structure problems with a stack, find the next greater or smaller element for every position in one pass, and explain the push-once, pop-once reason it runs in linear time.

    8 min read