Find two numbers that add up to a target in a sorted list, with one pointer at each end moving towards the other.
Python · intermediate · 6 min · 28 steps · free
def pair_with_sum(nums, target):
left, right = 0, len(nums) - 1
while left < right:
total = nums[left] + nums[right]
if total == target:
return (nums[left], nums[right])
if total < target:
left += 1
else:
right -= 1
return None
print(pair_with_sum([1, 3, 4, 6, 8, 11], 10))pair_with_sum(). Its body does not run yet: it runs each time the function is called.pair_with_sum(), with nums = [1, 3, 4, 6, 8, 11] and target = 10. It gets its own names.left is created with the value 0. right is created with the value 5.left < right is true, so the loop body runs.total == target is false, so the block under it is skipped.total < target is false, so the block under it is skipped.right left.left < right is true, so the loop body runs.total changes from 12 to 9.total == target is false, so the block under it is skipped.total < target is true, so the block under it runs.left right, to a bigger number.left < right is true, so the loop body runs.total changes from 9 to 11.total == target is false, so the block under it is skipped.total < target is false, so the block under it is skipped.right changes from 4 to 3.left < right is true, so the loop body runs.total changes from 11 to 9.total == target is false, so the block under it is skipped.total < target is true, so the block under it runs.left changes from 1 to 2.left < right is true, so the loop body runs.total changes from 9 to 10.total == target is true, so the block under it runs.pair_with_sum() has finished, so its names are gone. It prints (4, 6).Answer: O(n²)
Answer: Sorted
← Binary Search · Sliding Window →