FAANGPrep Sprint
Two Sum II - Input Array Is Sorted (LeetCode 167)
Two Sum II - Input Array Is Sorted (LeetCode 167): the integer array numbers is sorted in non-decreasing order and indexed from 1. Find the two entries whose sum equals target and return their positions.
Examples
2 + 7 = 9, and those values sit at positions 1 and 2 counting from 1, so the answer is [1, 2].
2 + 4 = 6, at positions 1 and 3 counting from 1, so the answer is [1, 3].
Problem Understanding
Two Sum II (also listed as Two Integer Sum II) is similar to the classic Two Sum, but with two key differences:
- The array is already sorted.
- You must return 1-based indices.
A brute force approach would be to check every pair, which is O(n²). However, the sorted property allows us to use the Two Pointers technique to solve it in linear time O(n).
Algorithm Strategy
- Initialize
leftat the start (index 0) andrightat the end (index n-1). - Calculate
current_sum = numbers[left] + numbers[right]. - If
current_sum == target, we found the pair! Return[left + 1, right + 1]. - If
current_sum < target, we need a larger sum. Since the array is sorted, movingleftto the right increases the sum. - If
current_sum > target, we need a smaller sum. Movingrightto the left decreases the sum.
Interactive Visualization
TARGET 9
START AT THE ENDS
L
0
1
2
R
3
Left
0
Right
3
Sum
:
Returns
:
Target 9: left starts at index 0, right at index 3
Next
numbers[0] + numbers[3] = 2 + 15 = 17
Sorted array
Target
Legend & Complexity
The values under L and R being added
The pair that sums to the target
Values outside the pointers: ruled out
Time
O(n)
Space
O(1)
Each step adds the values under L and R and moves one pointer toward the target; values outside the pointers are struck out, because no answer can use them.
Dry Run: nums = [2, 7, 11, 15], target = 9
| Iteration | Left (Index/Val) | Right (Index/Val) | Sum (L+R) | Comparison | Action |
|---|---|---|---|---|---|
| 1 | 0 / 2 | 3 / 15 | 17 | 17 > 9 (Too Big) | Decrement Right |
| 2 | 0 / 2 | 2 / 11 | 13 | 13 > 9 (Too Big) | Decrement Right |
| 3 | 0 / 2 | 1 / 7 | 9 | 9 == 9 (Match!) | Return [1, 2] |
Edge Cases & Common Mistakes
Edge Cases:
- No Solution: Ensure your code handles cases where no pair sums to the target (return empty vector/array).
- Array Constraints: Typically length >= 2.
Common Mistakes:
- 0-based vs 1-based: The problem asks for 1-based indices. Returning
[left, right]instead of[left+1, right+1]is a frequent bug! - Not using Sorted Property: Using a Hash Map (O(n) space) works but is explicitly suboptimal when O(1) space is required.
Solution
Two Sum II - Input Array Is Sorted Code
1/**2 * @param {number[]} numbers3 * @param {number} target4 * @return {number[]}5 */6var twoSum = function(numbers, target) {7 let left = 0;8 let right = numbers.length - 1;910 while (left < right) {11 let sum = numbers[left] + numbers[right];1213 if (sum === target) {14 return [left + 1, right + 1];15 } else if (sum < target) {16 left++;17 } else {18 right--;19 }20 }2122 return [];23};
Two Sum II - Input Array Is Sorted in Python, Java, C++, TypeScript and C
Two Sum II - Input Array Is Sorted in Python
def twoSum(numbers: List[int], target: int) -> List[int]:
left = 0
right = len(numbers) - 1
while left < right:
current_sum = numbers[left] + numbers[right]
if current_sum == target:
return [left + 1, right + 1]
elif current_sum < target:
left += 1
else:
right -= 1
return []Two Sum II - Input Array Is Sorted in Java
class Solution {
public int[] twoSum(int[] numbers, int target) {
int left = 0;
int right = numbers.length - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
return new int[]{left + 1, right + 1};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return new int[]{};
}
}Two Sum II - Input Array Is Sorted in C++
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int left = 0;
int right = numbers.size() - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
return {left + 1, right + 1};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return {};
}
};Two Sum II - Input Array Is Sorted in TypeScript
function twoSum(numbers: number[], target: number): number[] {
let left = 0;
let right = numbers.length - 1;
while (left < right) {
let sum = numbers[left] + numbers[right];
if (sum === target) {
return [left + 1, right + 1];
} else if (sum < target) {
left++;
} else {
right--;
}
}
return [];
}Two Sum II - Input Array Is Sorted in C
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
int left = 0;
int right = numbersSize - 1;
while(left < right) {
long long sum = (long long)numbers[left] + numbers[right];
if(sum == target) {
int* result = (int*)malloc(2 * sizeof(int));
result[0] = left + 1;
result[1] = right + 1;
*returnSize = 2;
return result;
} else if(sum < target) {
left++;
} else {
right--;
}
}
*returnSize = 0;
return NULL;
}