๐
Date: Feb 8, 2026
๐ฅ Topic: Problem Solving: Pair Sum (Two Pointers)
๐งฉ The Problem
Given a sorted vector and a target value, find two numbers that add up to the target.
Example: Arr = [2, 7, 11, 15], Target = 9
Result: 2 and 7 (Indices 0 and 1)
๐ก Approach: Two Pointers
Instead of checking every pair (O(n²)), we use a smart trick (O(n)).
1. Put pointer start at 0.
2. Put pointer end at last index.
3. If sum > target, decrease end (need smaller number).
4. If sum < target, increase start (need larger number).
๐ป Day 38 Code
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {2, 7, 11, 15};
int target = 9;
int s = 0, e = nums.size() - 1;
while(s < e) {
int pairSum = nums[s] + nums[e];
if(pairSum == target) {
cout << "Pair Found: " << nums[s] << ", " << nums[e] << endl;
break;
}
else if(pairSum > target) {
e--;
}
else {
s++;
}
}
return 0;
}
๐ญ Thoughts
This Two Pointer technique only works if the array is Sorted. It was magical to see O(n²) logic turn into O(n).
No comments:
Post a Comment