๐Ÿ“… 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).