Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Reusable problem patterns
EXPERIMENT 61 / 66

Move the boundary with a reason.

Use sorted order to eliminate candidate pairs without enumerating them all.

BY NAVAN SAMI◷ 8 MIN READSTRETCHALGORITHM

01 Model the idea

Two pointers are useful when moving one boundary can safely rule out a group of candidates. In sorted two-sum, a sum that is too small means the left value is too small even when paired with the largest remaining value. A sum that is too large similarly rules out the right value. That ordering argument makes each boundary movement safe.

THE THING THAT MUST STAY TRUE

No pair excluded by the current boundaries can meet the target.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
COMPARE the boundary sum with the target
MOVE left if too small, right if too large
STOP on a match or crossed boundaries

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

two_pointers.py
def two_sum(values, target):
    left, right = 0, len(values) - 1
    while left < right:
        total = values[left] + values[right]
        if total == target: return left, right
        if total < target: left += 1
        else: right -= 1
    return None
print(two_sum([2, 4, 7, 11, 15], 15))
↳ EXPECTED OUTPUT
(1, 3)
  1. 1

    The returned pair contains distinct indexes. The left<right condition prevents using one position twice.

  2. 2

    Every failed comparison removes at least one boundary, so there are at most linear many pointer moves.

  3. 3

    The input must be sorted. If you sort internally, the total cost and original-index contract change; storing original positions may be necessary.

04 Count the cost

TIME

O(n) on already sorted input

SPACE

O(1) auxiliary

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Test an absent target and a pair formed by equal values at distinct positions.

Reveal one possible solution +
one_possible_solution.py
def two_sum(values, target):
    left, right = 0, len(values) - 1
    while left < right:
        total = values[left] + values[right]
        if total == target: return left, right
        if total < target: left += 1
        else: right -= 1
    return None
print(two_sum([3, 3], 6))
print(two_sum([1, 2], 9))

06 Check your reasoning

QUICK SIGNAL CHECK

What justifies moving a boundary?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.