LeetMotion
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number.
Return the indices of the two numbers, 1-indexed. The solution must use only constant extra space.
numbers is sorted in non-decreasing order.Try every pair of indices and check if they sum to the target. Since the array is 1-indexed in the return value, we add 1 to each index.
i, iterate j from i+1 to the end.numbers[i] + numbers[j] == target, return [i+1, j+1].Why it's not optimal: O(n²) time. Since the array is sorted, we can do much better by exploiting the ordering with two pointers.
def twoSum(numbers, target): for i in range(len(numbers)): for j in range(i + 1, len(numbers)): if numbers[i] + numbers[j] == target: return [i + 1, j + 1]
Because the array is already sorted, we do not need to use $O(n)$ space for a Hash Map! We can place a pointer at the beginning (smallest possible value) and the end (largest possible value) and logically eliminate options.
L at the 0th index and R at the end.[L+1, R+1].
Discussion
…