Featured article for the topic Two pointers · picked by the needcode team
Two pointers: shrink the search space from both ends
needcode teamFeatured AuthorPosted · 1 min read
On a sorted array, two pointers turn an O(n²) pair search into O(n).
def two_sum_sorted(nums, target):
lo, hi = 0, len(nums) - 1
while lo < hi:
s = nums[lo] + nums[hi]
if s == target:
return lo, hi
if s < target:
lo += 1
else:
hi -= 1
return None
Each step discards one element that can't be part of any answer, so the loop runs at most n times.
Practice#
- Container with most water
- 3Sum
- Remove duplicates from a sorted array
Comments