✅ Find Pairs in Sorted Array with Given Sum in C++
Finding pairs in a sorted array that sum up to a specific target is a common problem in computer science. This tutorial demonstrates how to efficiently solve this using the two-pointer technique in C++.
📘 What You'll Learn
- Understanding the two-pointer technique
- Implementing an efficient solution in C++
- Optimizing time complexity to O(n)
📄 C++ Program: Find Pairs with Given Sum
#include <iostream>
#include <vector>
using namespace std;
void findPairsWithSum(const vector<int>& arr, int target) {
int left = 0;
int right = arr.size() - 1;
bool found = false;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) {
cout << "Pair found: " << arr[left] << " + " << arr[right] << " = " << target << endl;
found = true;
left++;
right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
if (!found) {
cout << "No pairs found with sum " << target << endl;
}
}
int main() {
vector<int> sortedArray = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int targetSum = 10;
findPairsWithSum(sortedArray, targetSum);
return 0;
}
✅ Sample Output
Pair found: 1 + 9 = 10 Pair found: 2 + 8 = 10 Pair found: 3 + 7 = 10 Pair found: 4 + 6 = 10
📘 Explanation
- Initialize two pointers: one at the start (
left
) and one at the end (right
) of the array. - Calculate the sum of the elements at these pointers.
- If the sum equals the target, print the pair and move both pointers inward.
- If the sum is less than the target, move the
left
pointer to the right to increase the sum. - If the sum is greater than the target, move the
right
pointer to the left to decrease the sum. - Continue this process until the
left
pointer is no longer less than theright
pointer.
Post a Comment