bhylu.com

Advertisements

DSA Two Pointers

Two pointers are useful when sorted order tells you which direction can improve a candidate. The movement rule needs a proof tied to the actual problem.

How it works

To find a pair with a required sum in ascending values, compare the outer pair. If its sum is too small, keeping the left value while reducing the right one cannot help, so advance left. If the sum is too large, reducing right is the useful move. This reasoning relies on sorted numeric input and finds one pair, not every possible pair or a count of duplicate combinations.

Run the code

Select Try in playground to load this complete source into the existing Python editor. It does not run automatically; choose Run when ready. These examples use only the Python standard library and small fictional inputs. They do not need database services, extra packages or personal files.

For local work, save the complete source as two-pointers.py and run python two-pointers.py. The local review uses Python 3.12.14; the browser uses the existing Pyodide 0.27.7 runtime. Keep inputs small, respect explicit table/tour budgets and account for recursion limits before increasing a fixture’s size.

Example

two-pointers.py

def pair_sum(values, target):
    left, right = 0, len(values) - 1
    while left < right:
        total = values[left] + values[right]
        if total == target:
            return values[left], values[right]
        if total < target:
            left += 1
        else:
            right -= 1
    return None

print(pair_sum([-2, 3, 5, 9], 8))
print(pair_sum([2], 4))

Expected result

(3, 5)
None

Three and five make the requested sum, while the one-item input cannot reuse the same position twice. The algorithm does not sort or mutate its input. If input ordering is unknown, include sorting cost or choose another suitable method.

Time, space and assumptions

Each boundary advances at most n positions, giving O(n) time and O(1) auxiliary storage after sortedness is established.

Consult the Python 3.12 standard-library reference for container and language contracts; an example result is not a proof of every possible input or real-world performance.

Advertisements