This is one of those problems where the clean idea matters more than the amount of code. For 167. Two Sum II - Input array is sorted, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are twoSum.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01/**
02Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
03
04The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
05
06Note:
07
08Your returned answers (both index1 and index2) are not zero-based.
09You may assume that each input would have exactly one solution and you may not use the same element twice.
10Example:
11
12Input: numbers = [2,7,11,15], target = 9
13Output: [1,2]
14Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
15**/
16
17/**
18Runtime: 12 ms, faster than 69.38% of C++ online submissions for Two Sum II - Input array is sorted.
19Memory Usage: 9.7 MB, less than 72.70% of C++ online submissions for Two Sum II - Input array is sorted.
20**/
21
22class Solution {
23public:
24 vector<int> twoSum(vector<int>& numbers, int target) {
25 int n = numbers.size();
26
27 int i = 0, j = n-1;
28
29 while(i < j){
30 if(numbers[i] + numbers[j] == target){
31 return {i+1, j+1};
32 }else if(numbers[i] + numbers[j] > target){
33 --j;
34 }else{
35 ++i;
36 }
37 }
38
39 return {0,0};
40 }
41};
Cost