Skip to contentKEEP THE CRAFTTHE SANCTUARY

Two Pointers

Use two coordinated indices when a comparison proves that an entire group of candidates can be discarded. Separate opposite-end search from read/write compaction, and explain the proof before choosing a movement.

4 practice exercises12 interview problems

Recognize it when A sorted sequence and a pair condition let the smallest or largest remaining value rule out several pairs at once.

Checking your account…

Two Pointers Code Labs

Start with the Work a Pair Search Repeats

After learning list indexing, imagine testing whether two different values sum to a target. A nested loop revisits many pairs. Sorted order supplies a stronger observation: if the smallest and largest remaining values sum too low, the smallest cannot succeed with any smaller partner. That proof lets one comparison reject a whole row of pairs.

Give Each Pointer a Meaning

The first Lab uses opposite ends of a closed unresolved interval. left identifies its smallest value and right its largest. Equality stops the search; a low total advances only left, and a high total decreases only right. The trace stores inspected pairs for explanation, so its output allocation differs from the constant working memory of the search itself.

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

Trace Pointer Decisions

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

Watch a High Sum Become an Exact Pair

Call the adjacent Lab with sorted values [2, 4, 7, 10] and target 11. The following rows follow its actual statements; the final trace contains only the pairs inspected.

Step Executed statement State Why
Initialize left, right = 0, len(values) - 1 left=0, right=3, trace=[] Both ends bound every candidate pair.
Inspect 2 and 10 total = values[left] + values[right] total=12 Even the smallest partner makes 10 too large.
Discard 10 right -= 1 left=0, right=2 No remaining value can pair with 10 to reach 11.
Inspect 2 and 7 trace.append([left, right, total]) trace=[[0,3,12],[0,2,9]] The new sum is recorded before its movement.
Discard 2 left += 1 left=1, right=2 With the largest remaining partner, 2 still falls short.
Find 4 and 7 if total == target: total=11, trace=[[0,3,12],[0,2,9],[1,2,11]] Equality takes the break branch; no further candidate is needed.
Return return trace three inspected pairs The Lab exposes movement rather than returning just the matching pair.
Print Output
print(two_pointer_decisions([2, 4, 7, 10], 11)) [[0, 3, 12], [0, 2, 9], [1, 2, 11]]

Turn a Trace into an Answer

The next Lab returns the endpoint indices when equality is reached. These are positions in the supplied sorted list. Moving both endpoints after a failed comparison discards candidates without proof, while allowing left == right reuses one item. Empty and single-item inputs therefore contain no pair.

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. values is sorted in nondecreasing order.

Public tests

  • Find a pair without reuse

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

Find a Sorted Pair Sum

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 []

Choose the Pointer Roles Before the Pattern Name

Opposite pointers eliminate candidate pairs. Same-direction pointers instead separate a reader from a writer and finalize an output prefix. A sliding window maintains an aggregate for every element between two boundaries. Choose the role that matches the question; a two-index loop is not automatically interchangeable with either of the others.

For unsorted two-sum with original positions, a complement hash map avoids sorting away those positions. If sorting is allowed, include O(n log n) preparation and clarify whether it mutates the input. For one sorted existence query, the O(n) scan needs only constant working state.

Explain Pair Elimination in an Interview

Explain which candidates a comparison rejects before writing the movement. Then use the trace to check one low and one high branch, and use the answer Lab to check the no-pair case. Maximum Container Area(opens in a new tab) has an endpoint movement proof too, but it follows from the limiting height rather than sorted pair sums; transfer the proof habit instead of copying this condition.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Expand around the center

Pick a center, grow while the ends match; try odd and even.

You look for palindromic substrings: every palindrome grows outward from a middle letter or a middle gap.

Trigger words

  • longest palindromic substring
  • palindromic substrings
  • count palindromes
def longest_palindrome(s):
    def expand(left, right):
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        return s[left + 1:right]          # the loop stepped one too far on each side

    best = ""
    for center in range(len(s)):
        odd = expand(center, center)          # "aba": the middle is one letter
        if len(odd) > len(best):
            best = odd
        even = expand(center, center + 1)     # "abba": the middle is a gap
        if len(even) > len(best):
            best = even
    return best

Spot it when

  • 'Longest palindromic substring', 'count palindromic substrings'.
  • n is a few thousand, so O(n^2) is fine.

Remember

  • There are 2n - 1 centers (n letters and n - 1 gaps), so the work is O(n^2) time and O(1) extra space.
  • Both pointers move outward together; stop at the first mismatch or at an edge.

How problems bend it

  • Count palindromic substrings: Add 1 to a counter inside the while loop: every successful step outward is one more palindrome.
  • Return positions instead of text: Make expand return (left + 1, right) and compare lengths right - left.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
Sorted pair-sum scanO(n)O(n)Each pointer moves inward at most n times; the second Lab returns only one pair.

Space

O(1) working state; the tracing Lab additionally stores O(n) inspected pairs.

Assumptions

  • The Lab assumes sorted input. Sorting first costs O(n log n) and may change the meaning of original indices.
  • Python list indexing accesses one element; sorted(values) builds a new list whereas values.sort() mutates the caller.

Invariants Worth Saying Aloud

  1. In the sorted pair-sum Lab, every not-yet-rejected pair uses indices between left and right.
  2. left < right prevents using one item twice; each failed comparison removes exactly one endpoint.

When To Use Or Avoid Two Pointers

Use It When

  • Search a sorted sequence for a pair without repeatedly restarting the second index.
  • Compact or partition a sequence when each pointer has a clear role and discarded work cannot become useful again.

Choose Another Tool When

  • Use a hash map for unsorted complement lookup when original indices must be preserved and O(n) extra storage is acceptable.
  • Use a direct nested scan when no ordering or monotone rejection proof exists; two indices alone do not make it linear.

Common Pitfalls

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

Moving the wrong endpoint after a high sum

With sorted [1, 4, 8] and target 5, a high endpoint sum rules out 8. Advancing left skips the valid pair [1, 4].

Prevent it: When the total is too high, keep the smallest remaining value and remove the largest endpoint.

Avoid

left += 1

Use instead

right -= 1

Reusing a single item as a pair

On [3], permitting equal indices incorrectly claims that one element can supply both addends of target 6.

Prevent it: Require left < right for a pair of distinct positions, including the equality check.

Avoid

found = left <= right and values[left]+values[right] == target

Use instead

found = left < right and values[left]+values[right] == target

Sorting away the caller's original positions

Sorting [6, 2, 4] in place changes which value occupies each original index before a result is reported.

Prevent it: If mutation is not permitted, sort a separate list and state whether returned positions refer to that list or use a hash map for original positions.

Avoid

values.sort()

Use instead

ordered = sorted(values)

Reviewed References

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