167. Two Sum II - Input Array Is Sorted
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Two Pointers
- Time
- —
- Space
- —
Standard Solution (C++)
SummaryGiven a 1-indexed sorted array and a target value, find the two distinct positions whose elements sum to the target, returning their 1-based indices as a pair guaranteed to have exactly one solution.
Approach
- Place one pointer at the left end and one at the right end of the sorted array.
- If their sum equals the target, return the 1-based indices immediately.
- If the sum is too large, move the right pointer left to reduce it; if too small, move the left pointer right to increase it.
- The sorted order guarantees convergence and that no solution is skipped — each step either finds the answer or eliminates values that cannot participate in any valid pair.
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int lo = 0, hi = static_cast<int>(numbers.size()) - 1;
while (lo < hi) {
int sum = numbers[lo] + numbers[hi];
if (sum == target) {
return {lo + 1, hi + 1}; // convert to 1-based indices
} else if (sum < target) {
++lo; // need a larger value
} else {
--hi; // need a smaller value
}
}
return {}; // problem guarantees exactly one solution; never reached
}
};
Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i=0;
int j=numbers.size()-1;
while(i<j){
int sum=numbers[i]+numbers[j];
if(sum==target)
return {i+1, j+1};
else if(sum>target)
j--;
else
i++;
}
return {};
}
};
// Time: O(n)
// Space: O(1) My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.