Two Sum II - Input Array Is Sorted – Solution & Complexity
Solution Walkthrough
Step 1: Use the sorted order
- The unsorted Two Sum needs a hash map, but here the array is already sorted.
- A sorted array lets two converging pointers decide, in one comparison, whether the current pair is too small or too large.
- Remember the required output is 1-based, so add one to each final index.
Step 2: Converge two pointers
- Start
loat the first element andhiat the last. - If
numbers[lo] + numbers[hi]equals the target, you found the unique answer. - If the sum is too small, the only way to grow it is to move
loright; if it is too large, movehileft.
- Start
Step 3: Why moving a pointer never skips the answer
- If the sum is too small, every pair using the current
lowith a smallerhiis even smaller, solocan never pair with anything left ofhi— safe to advancelo. - The symmetric argument justifies decrementing
hi. - Because exactly one answer exists, the pointers are guaranteed to meet it before crossing.
- If the sum is too small, every pair using the current
Step 4: Brute-force baseline
- Checking every pair also works and needs no extra space, but costs
O(n^2)time. - It is a useful correctness reference for the two-pointer version.
- Checking every pair also works and needs no extra space, but costs
Step 5: Optimal two-pointer solution
- Walk the two pointers toward each other, returning the 1-based indices on a match.
- Time is
O(n)and extra space isO(1).
Step 6: Common mistakes
- Returning 0-based indices instead of adding one for the 1-based contract.
- Returning
[hi + 1, lo + 1]— the smaller index must come first. - Using a nested loop when the sorted input makes the linear scan available.