Move Two Positions With a Purpose

When you compare the ends of a sequence, two index positions can help you keep track of what’s left to check. After each comparison, you move one or both positions and keep the part that might still contain your answer.

Say you have the ordered values [2, 5, 8, 12] and you’re looking for a pair that sums to 13. The outer values add up to 14, which is too much, so you can move the right position inward:

Four sorted values, 2, 5, 8, and 12, with pointers at both ends and an arrow moving the right pointer from 12 to 8.
A Smaller Right Value After an Oversized Sum

Why is it safe to discard 12? Even its smallest available partner, 2, makes the sum too large, and every other partner would only increase it. Keep in mind that this reasoning depends on the input being sorted. With unordered values, the same move could throw away the exact pair you need.

Both positions move toward each other, so together they make at most a linear number of moves. You keep only the indices and a few temporary values, which takes O(1) extra space. Watch out for list and string slices, though. A slice can quietly create a copy even when the expression looks short.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.