Two Pointers Meet Inside A Sorted Array
Walk both ends of a sorted array inward: move the left pointer when the pair sum is too small, the right one when it is too big.
Code
# Two pointers on a sorted array: start at both ends and walk inward.
# If the pair sum is too small only a bigger left value can help, and
# if it is too big only a smaller right value can — so one linear pass
# either finds the pair or proves none exists.
def pair_with_sum(values, target):
left, right = 0, len(values) - 1
while left < right:
current = values[left] + values[right]
if current == target:
return values[left], values[right]
if current < target:
left += 1
else:
right -= 1
return None
ordered = [2, 3, 5, 8, 11, 15]
print(pair_with_sum(ordered, 13))
print(pair_with_sum(ordered, 10))
print(pair_with_sum(ordered, 40))Output
Captured from a sandboxed run of this snippet in the build pipeline.
(2, 11)
(2, 8)
NoneWhat the code does
Everything that moves lives in the function pair_with_sum.
The loop while left < right is the only repeated construct.
Watch out for
- Only built-in APIs, which leaves no supply chain to vet.
Applying it
Entry signature: def pair_with_sum(values, target)
pair_with_sum is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.JSON Pointer EvaluatorEvaluate RFC 6901 JSON Pointer strings against a JSON document to extract the referenced value, with tilde-slash escape handling.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `pair_with_sum` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.