Given a list of integers sorted in non-decreasing order and a target value, find two positions whose values add up to the target.
Implement two_sum_sorted(nums, target). Start one pointer at the left end and one at the right end. If the sum is too small, move the left pointer right; if it is too large, move the right pointer left. Return the pair of indices (i, j) as a tuple when a match is found, or None if no pair exists.
You may assume there is at most one valid answer.
def two_sum_sorted(nums, target):
"""Return a pair of indices (i, j) with nums[i] + nums[j] == target.
The input list is sorted in non-decreasing order. Move two pointers
inward from both ends. Return None if no pair exists.
"""
# TODO: use a left and a right pointer and move them inward
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Given a list of integers sorted in non-decreasing order and a target value, find two positions whose values add up to the target.
Implement two_sum_sorted(nums, target). Start one pointer at the left end and one at the right end. If the sum is too small, move the left pointer right; if it is too large, move the right pointer left. Return the pair of indices (i, j) as a tuple when a match is found, or None if no pair exists.
You may assume there is at most one valid answer.
Press Run Tests or ββ© to check your solution.