Two Sum II — Sorted
Medium
Two PointersBinary Search
Problem
Given a 1-indexed sorted array nums (ascending) and a target, return the 1-indexed positions of the two numbers that sum to target. There is exactly one solution.
Example 1
Input: nums = [2,7,11,15], target = 9
Output: [1, 2]
Example 2
Input: nums = [2,3,4], target = 6
Output: [1, 3]
Example 3
Input: nums = [-1,0], target = -1
Output: [1, 2]
Constraints
- 2 ≤ nums.length ≤ 3·10⁴
- −1000 ≤ nums[i] ≤ 1000
- sorted ascending
Approach — Two Pointers
This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(1) extra space.
Solution code
Java
class Solution {
public int[] twoSum(int[] nums, int target) {
int l = 0, r = nums.length - 1;
while (l < r) {
int s = nums[l] + nums[r];
if (s == target) return new int[]{ l + 1, r + 1 };
if (s < target) l++;
else r--;
}
return new int[]{};
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Two Sum II — Sorted interactively → ← All solutions