Use two moving positions to examine a sorted sequence without checking every pair.
What You Will Learn
The two-pointer technique often starts with one pointer at each end of a sorted list. Move the pointer that can help approach your target based on the current comparison. This can reduce a pair search from quadratic work to a single pass, but it relies on the data being sorted and the movement rule being correct.
Time complexity assumes a specific input structure. Include setup work such as sorting or building a lookup table when comparing complete solutions.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
def pair_sum(sorted_values, target):
left, right = 0, len(sorted_values) - 1
while left < right:
total = sorted_values[left] + sorted_values[right]
if total == target:
return sorted_values[left], sorted_values[right]
if total < target:
left += 1
else:
right -= 1
return None
print(pair_sum([1, 3, 4, 7, 10], 11))
How the Example Works
- The function pair_sum defines reusable behavior; its body executes when it is called, not when it is declared.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression pair_sum([1, 3, 4, 7, 10], 11) prints (1, 10). Compare that result with the rule above before you change the argument.
Expected output from the example:
(1, 10)
When You Would Use This
This technique matters when a program handles larger queues, sorted records, or repeated lookups. Choose the data structure based on actual operations and the preconditions the algorithm requires. Verify boundary inputs before optimizing for speed.
Practice: Modify the Code
Test a target for which no pair exists and a list containing negative numbers.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Using this movement strategy on unsorted values without changing the algorithm.
- Continuing when left meets right and accidentally using the same index twice.
Key Takeaways
- Use two moving positions to examine a sorted sequence without checking every pair.
- The two-pointer technique often starts with one pointer at each end of a sorted list.
- Apply this operation only after checking the assumptions and input conditions shown in the example.