Skip to content
Hello Python
Pattern2 Practice5 Interview

Two Pointers

Coordinate two indices to eliminate candidate pairs or partition an ordered search space. Learn its decision rule, maintained state, Python cost model, and transfer from a focused drill to a full Interview Problem.

Recognize it when

Consider Two Pointers when the prompt's constraints and required operations match this shape: Coordinate two indices to eliminate candidate pairs or partition an ordered search space.

Pybit demonstrates the Two Pointers decision pattern in a professional coding interview workspace.
On this page · Let Order Eliminate Pairs

Checking your account…

Sign in to save your code and progress across devices. The lesson and problem statement remain public.

Two Pointers Code Labs

Let Order Eliminate Pairs

On sorted input, comparing the endpoint pair eliminates many candidates at once. If the sum is too small, no pair using the current left value and a smaller right value can reach the target; advance left. The symmetric argument moves right when the sum is too large.

State the Pointer Invariant

The closed interval from left through right contains every unresolved candidate. Everything outside it has been rejected by a comparison proof. Both pointers move monotonically, so no pair is reconsidered.

Trace Pointer Decisions

Reference
def two_pointer_decisions(values, target):
    left, right = 0, len(values) - 1
    trace = []
    while left < right:
        total = values[left] + values[right]
        trace.append([left, right, total])
        if total == target:
            break
        if total < target:
            left += 1
        else:
            right -= 1
    return trace
Practice

Implement two_pointer_decisions(values, target). values is sorted. Return [left, right, sum] for each inspected pair until target is found or pointers cross.

Public tests

  • Trace justified moves

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Move Exactly One Boundary

Each comparison must justify the next movement. Moving both endpoints can skip a solution; moving neither prevents termination. Duplicates may require deliberate skipping only when the output contract asks for unique values.

Find a Sorted Pair Sum

Reference
def sorted_pair_sum(values, target):
    left, right = 0, len(values) - 1
    while left < right:
        total = values[left] + values[right]
        if total == target:
            return [left, right]
        if total < target:
            left += 1
        else:
            right -= 1
    return []
Practice

Implement sorted_pair_sum(values, target). Return the first endpoint indexes [left, right] found by opposite pointers, or [] if none exists.

Public tests

  • Find a pair without reuse

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Choose Two Pointers or Hashing

Use two pointers when input is sorted or can be sorted and relative order is not part of the answer. Use hashing for unsorted one-pass complement lookup when original indexes matter. Count an initial sort as O(n log n), even though the pointer scan is O(n).

Explain It in an Interview

Say: “Sorted order lets this comparison discard every candidate beyond one boundary, so I move only that pointer.” Each pointer moves at most n times, giving O(n) scan time and O(1) auxiliary space. Maximum Container Area(opens in a new tab) uses a different comparison but the same elimination proof.

Python Version Note

Python 3.11+

The examples use the standard Python syntax and containers supported by the browser Judge; the Two Pointers invariant is independent of a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Two Pointers decision loopO(n)O(n)Sorted order lets one successful smallest-plus-largest comparison certify several pairs with the same left endpoint. Every pair outside [left, right] has already been counted or proven too large, and no unresolved pair is skipped.

Space

O(1) for the focused Discard Pairs with Two Pointers implementation.

Assumptions

  • When the endpoint sum is within the limit, pairing left with every index through right is also valid, adding exactly right-left pairs. Otherwise every pair using right is too large, so decrementing right discards no valid pair.
  • The bound includes real Python operations; no repeated slicing, linear list membership, or hidden sorting is treated as free.

Invariants Worth Saying Aloud

  1. State the precise Two Pointers invariant before coding and preserve it after every update, traversal step, or recursive return.
  2. The unresolved interval still contains every possible answer.
  3. Each pointer moves monotonically and never revisits discarded work.
  4. Sorted order lets one successful smallest-plus-largest comparison certify several pairs with the same left endpoint. Preserve this property after every transition.
  5. Every pair outside [left, right] has already been counted or proven too large, and no unresolved pair is skipped. Preserve this property after every transition.

When To Use Or Avoid Two Pointers

Use It When

  • Use Two Pointers when the prompt exposes the ordering, monotonicity, recurrence, or constraint that makes this decision safe.
  • Use it when the unresolved interval still contains every possible answer.

Choose Another Tool When

  • Avoid Two Pointers when its decision rule cannot eliminate work or preserve the required state.
  • Avoid forcing the label onto a prompt whose simpler direct scan already meets the constraints.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Moving state without a proof

Applying the pattern without proving its ordering, monotonicity, or window invariant can silently miss valid candidates.

Prevent it: Write the decision rule beside the loop and verify it against Discard Pairs with Two Pointers before optimizing.

Avoid

def count_pairs_below(values, limit):
    pass

Use instead

def count_pairs_below(values, limit):
    left, right = 0, len(values) - 1
    count = 0
    while left < right:
        if values[left] + values[right] < limit:
            count += right - left
            left += 1
        else:
            right -= 1
    return count

Breaking the maintained state

Counts only the current endpoint pair instead of all right-left valid partners certified by sorted order.

Prevent it: Use the public tests and preserve this state: The unresolved interval still contains every possible answer.

Avoid

def count_pairs_below(values, limit):
    left, right = 0, len(values) - 1
    count = 0
    while left < right:
        if values[left] + values[right] < limit:
            count += 1
            left += 1
        else:
            right -= 1
    return count

Use instead

def count_pairs_below(values, limit):
    left, right = 0, len(values) - 1
    count = 0
    while left < right:
        if values[left] + values[right] < limit:
            count += right - left
            left += 1
        else:
            right -= 1
    return count

Hiding Python work in the hot path

Python slicing, copying, membership in lists, or repeated sorting inside the loop can invalidate the intended complexity.

Prevent it: Count every slice, copy, sort, membership check, and container update before claiming O(n).

Avoid

def count_pairs_below(values, limit):
    left, right = 0, len(values) - 1
    count = 0
    while left < right:
        if values[left] + values[right] < limit:
            count += 1
            left += 1
        else:
            right -= 1
    return count

Use instead

def count_pairs_below(values, limit):
    left, right = 0, len(values) - 1
    count = 0
    while left < right:
        if values[left] + values[right] < limit:
            count += right - left
            left += 1
        else:
            right -= 1
    return count

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.