03
Triplets / k-sum (Two Pointers Sub-pattern)
Find triplets (or quadruplets) with a target sum: sort, fix one element, and solve the rest as a two-pointer pair problem.
Signals in the problem statement
- ›
"three numbers that add up to…"
- ›
"all unique triplets"
- ›
"closest to target"
- ›
"count triangles"
What makes it different
One outer loop on top of opposite-ends. The hard part is skipping duplicates so each answer appears once.
Questions
ordered from “learn the idea” to “recognise it without help”- 1Triplet Sum in ArrayWalkthroughMediumBasic Anchor·GeeksforGeeks
- 23SumWalkthroughMediumBasic Reinforcement·LeetCode #15
- 33Sum ClosestWalkthroughMediumSlight Variation·LeetCode #16
- 4Valid Triangle NumberWalkthroughMediumMedium·LeetCode #611
- 54SumWalkthroughMediumPattern Transfer·LeetCode #18
- 63Sum With MultiplicityWalkthroughMediumTricky / Edge Case·LeetCode #923
Template
k-sum-template.cpp
// Triplets: sort, fix one element, then run opposite-ends two pointers on the rest.
vector<vector<int>> threeSum(vector<int> a, int target) {
sort(a.begin(), a.end());
vector<vector<int>> res;
int n = a.size();
for (int i = 0; i < n - 2; i++) {
if (i > 0 && a[i] == a[i - 1]) continue; // same fixed value → same triplets
int left = i + 1, right = n - 1;
while (left < right) {
long long sum = (long long)a[i] + a[left] + a[right];
if (sum < target) left++;
else if (sum > target) right--;
else {
res.push_back({a[i], a[left], a[right]});
while (left < right && a[left] == a[left + 1]) left++; // skip duplicates
while (left < right && a[right] == a[right - 1]) right--;
left++, right--;
}
}
}
return res;
}Remember this · Two Pointers
Trigger
Sorted array, pairs/triplets with a target, comparing from both ends, compacting an array in place.
Think
If I compare the elements at two positions, can I safely discard one side?
Key question
Which pointer moves, and why can the skipped elements never be the answer?