Sponsored
Sponsored
This approach utilizes a two-pointer technique taking advantage of the sorted nature of the input array. The first pointer starts at the beginning of the array while the second starts at the end. By evaluating the sum at these two pointers, you can determine how to move the pointers:
This method operates in O(n) time and uses O(1) additional space.
Time Complexity: O(n)
Space Complexity: O(1)
1var twoSum = function(numbers, target) {
2 let left = 0, right = numbers.length - 1;
3 while (left < right) {
4 const sum = numbers[left] + numbers[right];
5 if (sum === target) {
6 return [left + 1, right + 1];
7 } else if (sum < target) {
8 left++;
9 } else {
10 right--;
11 }
12 }
13 return []; // Unneeded by constraints
14};
In JavaScript, this solution works by managing two pointers. It capitalizes on inherent array manipulation abilities in JS to keep the solution concise while moving pointers similar to other approaches.
This approach also takes advantage of the sorted array, integrating binary search for a more theoretically robust approach. For every element in the array, a binary search is employed to find the complement such that the sum is equal to the target:
i
.target - numbers[i]
.Time Complexity: O(n log n) (due to binary search)
Space Complexity: O(1)
The C solution incorporates a binary search helper function to look for the complement of each element from the remaining array indices. Once found, it returns the indices incremented by one, adhering to the input constraints.