Problem Description
You are given an integer array nums sorted in ascending order.
Write a function twoSum that finds two numbers in the array whose sum equals the target number target.
The function should return an array with the indices of the elements that satisfy the condition.
Indices start at one.
Constraints
- The array contains from 2 to 3 * 104 unique values
- Values are in the range from -1000 to 1000
- The array is sorted in ascending order
targetis in the range from -1000 to 1000- There is always exactly one solution
Examples
Input
nums = [2, 5, 7, 15]
target = 9Answer: [1, 3]
The sum of 2 and 7 is 9, so index1 = 1 and index2 = 3. We return [1, 3].
Solution
The extra conditions make this problem much simpler:
- the array is sorted in ascending order;
- there are no duplicate values in the array.
Thanks to these conditions, we can solve the problem with two pointers using the following algorithm.
- Create two pointers that store indices. Set
leftto 0 andrightto the index of the last element. - Run a loop that stops when
leftbecomes greater than or equal toright, i.e. when the pointers meet. - On each iteration compute the sum of the elements at
leftandrightand compare it withtarget:- If the sum equals
target, we've found the numbers. Return their indices, adding one to each. - If the sum is greater than
target, we've added numbers that are too large and need smaller ones. We can decrease the sum by taking the number to the left of the one atright. Since the array is sorted in ascending order and has no duplicates, the number to the left ofrightis guaranteed to be smaller. Decrementrightby 1. - If the sum is less than
target, we've added numbers that are too small and need larger ones. We can increase the sum by taking the number to the right of the one atleft. Since the array is sorted in ascending order and has no duplicates, the number to the right ofleftis guaranteed to be larger. Incrementleftby 1.
- If the sum equals
This way we go through all the relevant combinations and find the answer.
export const twoSum = (nums: number[], target: number): number[] => {
// Set the left pointer to index zero
let left = 0;
// Set the right pointer to the index of the last element
let right = nums.length - 1;
// Loop until `left` and `right` meet
while (left < right) {
const sum = nums[left] + nums[right];
if (sum === target) {
return [left + 1, right + 1];
} else if (sum > target) {
right--;
} else {
left++;
}
}
// If nothing was found, return [-1, -1]
return [-1, -1];
};Complexity Analysis
n is the number of elements in the array.
Time Complexity
O(n), since in the worst case we go over all elements of the array.
Space Complexity
O(1), since we only use a few variables to store the indices and the sum.