Skip to contentKEEP THE CRAFTTHE SANCTUARY

Opposite-direction Pointers

Move inward from both ends when sorted order or mirror symmetry justifies each discarded position. Pair sums and palindrome checks share boundary movement but require different stopping and normalization rules.

1 practice exercise6 interview problems

Recognize it when A sorted pair sum can rule out the smallest or largest unresolved endpoint.

Checking your account…

Opposite-direction Pointers Code Labs

Let the Two Ends Answer Different Questions

Two pointers can begin at the extremes of an indexable sequence without copying it. For a sorted pair sum, the ends delimit possible pairs. For a palindrome, they delimit the characters still needing comparison. Start by stating which of these meanings your bounds have; their movement rules follow different proofs.

Reject an Endpoint with Sorted Order

If even the smallest remaining value makes the largest too large, no other remaining partner can rescue that largest value. Decrease right. If the sum is too small, increase left because all smaller partners also fail with that smallest value. Equality must be inspected before changing either endpoint.

Trace Opposite Pointer Decisions

Reference
def inward_trace(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 inward_trace(values,target). values is sorted. Return [left,right,sum] until the pair is found or pointers meet.

Public tests

  • Move the provably weak side

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

Trace Opposite Pointer Decisions

def inward_trace(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

Trace Two Rejections Before a Pair

Run inward_trace on [2, 5, 8, 12] with target 13. The first two unequal comparisons justify different movements.

Step Executed statement State Why
Set endpoints left,right=0,len(values)-1; trace=[] left=0, right=3 The candidate pair uses two different positions.
Record 14 total=values[left]+values[right]; trace.append([left,right,total]) trace=[[0,3,14]] The smallest remaining partner still makes 12 too high.
Reject right right-=1 left=0, right=2 Sorted order rules out all remaining pairs using 12.
Record 10 total=values[left]+values[right]; trace.append([left,right,total]) trace=[[0,3,14],[0,2,10]] The largest remaining partner cannot raise 2 to the target.
Reject left left+=1 left=1, right=2 Every other partner for 2 is smaller still.
Match 13 if total==target: break trace=[[0,3,14],[0,2,10],[1,2,13]] Equality resolves this existence search before any further move.
Print Output
print(inward_trace([2, 5, 8, 12], 13)) [[0, 3, 14], [0, 2, 10], [1, 2, 13]]

Skip Before Comparing a Palindrome

The text Lab finds the next alphanumeric character at each end, compares their lowercase forms, and then advances both ends. left < right belongs in each skip guard because punctuation-only text may have no significant pair. A single middle character needs no comparison. This Lab uses Python’s Unicode-aware character classification and lowercase behavior, rather than promising locale-specific normalization.

Check a Normalized Palindrome

Reference
def is_normalized_palindrome(text):
    left,right=0,len(text)-1
    while left<right:
        while left<right and not text[left].isalnum(): left+=1
        while left<right and not text[right].isalnum(): right-=1
        if text[left].lower()!=text[right].lower(): return False
        left+=1; right-=1
    return True
Practice

Implement is_normalized_palindrome(text). Ignore non-alphanumeric characters and case using opposite pointers without building a normalized copy.

Public tests

  • Skip punctuation at both boundaries

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

Check a Normalized Palindrome

def is_normalized_palindrome(text):
    left,right=0,len(text)-1
    while left<right:
        while left<right and not text[left].isalnum(): left+=1
        while left<right and not text[right].isalnum(): right-=1
        if text[left].lower()!=text[right].lower(): return False
        left+=1; right-=1
    return True

Resolve Output Semantics Before Skipping

For pair existence, equality ends the scan. Enumerating all pairs, counting all index pairs, and producing unique value pairs need different equality and duplicate rules. Do not transfer a duplicate-skipping rule from one output contract into another. Palindrome equality allows both boundaries to move because that exact mirrored pair has been resolved.

Defend the Boundary Choice in an Interview

Binary search is appropriate when one sorted or monotone boundary is the answer. Opposite pointers are appropriate when two endpoints jointly form a candidate or mirror each other. Include any initial sort in the time bound; character skipping and a sorted pair scan themselves take O(n). In practice, explain one specific rejected endpoint or one resolved character pair before naming the pattern.

Template To Memorize

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

Two pointers from both ends

Sorted pair? Too small, move left in; too big, move right in.

The input is sorted (or symmetric) and you look for a pair, or you check a string from the outside in.

Trigger words

  • sorted + pair sum
  • two sum ii
  • three sum
  • valid palindrome
  • reverse a string
  • most water
  • from both ends
def pair_with_sum(nums, target):  # nums is sorted
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return [left, right]
        if total < target:
            left += 1             # need a bigger sum
        else:
            right -= 1            # need a smaller sum
    return []

Spot it when

  • Sorted array and a target sum.
  • Palindrome checks.
  • Maximize something between two walls.

Remember

  • Each move throws away one candidate that can no longer be part of the answer.
  • The loop runs while left < right, so every element is looked at once: O(n).

How problems bend it

  • Three numbers (3Sum): Sort, fix nums[i] in an outer loop, run this template on the rest, and skip equal neighbours to avoid duplicates.
  • Container with most water: Measure the area, then move the shorter wall inward.
  • Palindrome: Compare s[left] and s[right]; skip characters that do not count.
  • Search a matrix sorted by rows and columns: Start at the top-right corner: value too big, move left; too small, move down.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
Inward pair or character scanO(n)O(n)Each boundary advances toward the center at most n times; punctuation skipping does not rescan passed characters.

Space

O(1) working state for the palindrome Lab; the pair-trace output uses O(n) space.

Assumptions

  • The pair Lab requires sorted input. The character Lab applies isalnum and lower per character rather than building a normalized string.
  • Python negative indices select existing characters, so every punctuation-skip loop must test the boundaries before indexing.

Invariants Worth Saying Aloud

  1. In pair search, every candidate not ruled out has both indices inside the current boundaries.
  2. In palindrome search, all significant characters already passed at opposite ends matched after the stated normalization.

When To Use Or Avoid Opposite-direction Pointers

Use It When

  • Search sorted pairs when the target comparison proves which endpoint cannot participate.
  • Check mirrored characters when the next meaningful symbol can be found by skipping toward the center.

Choose Another Tool When

  • Use binary search for one monotone threshold rather than a coupled pair of endpoints.
  • Do not apply sorted-sum movement to unsorted input or discard duplicate values when the output needs multiplicity.

Common Pitfalls

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

Skipping punctuation past the center

An unguarded skip on punctuation-only text runs beyond the string instead of recognizing that no significant pair remains.

Prevent it: Check left < right before every indexing step in a skip loop.

Avoid

while not text[left].isalnum():
    left += 1

Use instead

while left < right and not text[left].isalnum():
    left += 1

Comparing case before normalization

The significant characters in Aa match under the stated case-insensitive contract, but a raw comparison rejects them.

Prevent it: Apply the same promised normalization to both endpoints before comparing.

Avoid

matched = text[left] == text[right]

Use instead

matched = text[left].lower() == text[right].lower()

Moving before checking equality

The endpoints [1, 10] already satisfy target 11; moving both first changes the candidate to [3, 7] and discards the answer.

Prevent it: Evaluate equality on the current pair before any movement.

Avoid

left += 1
right -= 1
found = values[left]+values[right] == target

Use instead

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

Reviewed References

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