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.

PythonData Integrity

Code

snippet
# 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)
None

What 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

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.