After struggling with pointer movement logic in earlier problems, Two Sum II finally felt… clean.
This was the moment where:
- Pointer movement made sense
- Conditions felt logical
- And the solution matched the intuition perfectly
This article explains the approach, the code, and why the logic works.
Problem: Two Sum II — Input Array Is Sorted
Description
You are given a sorted array of integers and a target value.
Find two numbers such that they add up to the target and return their 1-indexed positions.
Example
Input: [2, 7, 11, 15]
Target: 9
Output: [1, 2]
🧠 Why Two Pointer Works Here
Key observations:
- The array is sorted
- We are searching for a pair
- Brute force would be O(n²)
- Two pointers reduce it to O(n)
This is a textbook Opposite Direction Two Pointer problem.
✍️ Simple Approach (English)
- Place left pointer at the start
- Place right pointer at the end
- Calculate the sum of both values
- Decide pointer movement based on comparison with target
🔑 Pointer Movement Rules (This Is the Core)
| Condition | Action | Reason |
|---|---|---|
| sum < target | move left | need a bigger value |
| sum > target | move right | need a smaller value |
| sum == target | store result | solution found |
This logic guarantees correctness because the array is sorted.
💻 C++ Implementation
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v = {2, 7, 11, 15};
vector<int> res(2, 0);
int target = 9;
int left = 0, right = v.size() - 1;
while (left < right) {
int sum = v[left] + v[right];
if (sum < target)
left++;
else if (sum > target)
right--;
else {
// 1-indexed answer
res[0] = left + 1;
res[1] = right + 1;
break;
}
}
for (int x : res)
cout << x << " , ";
return 0;
}
✅ Why This Code Is Correct
✔️ Correct Pointer Movement
if(sum < target) left++;
else if(sum > target) right--;
Too small → move left forward
Too large → move right backward
This uses the sorted property correctly.
✔️ Correct Indexing
res[0] = left + 1;
res[1] = right + 1;
The problem requires 1-based indexing, and this is handled perfectly.
✔️ Early Exit
break;
Once the pair is found, no unnecessary work is done.
⏱️ Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1) (ignoring output array)
This is optimal.
🧠 What I Learned From This Problem
1️⃣ Sorted Array = Controlled Pointer Movement
Sorting (or already sorted data) gives you directional power.
2️⃣ Two Pointer Is About Decisions, Not Loops
Every pointer move must answer one question:
“How do I get closer to the target?”
3️⃣ This Is the Foundation Pattern
Once this is clear, problems like:
Container With Most Water
Reverse Vowels
Valid Palindrome
become much easier.
🌱 Final Thought
Two Sum II is not a hard problem.But it’s an important one.
If this logic feels natural now,
you’ve officially crossed the Two Pointer thinking barrier 🚀
Top comments (0)