On this page · Let the Two Ends Answer Different Questions
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.
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.
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
Python 3.11+
Python negative indices select existing characters, so every punctuation-skip loop must test the boundaries before indexing.