2Brute2Best
🔥0
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”
  1. 1
    Triplet Sum in Array
    Basic Anchor·GeeksforGeeks
    Medium
  2. 2
    3Sum
    Basic Reinforcement·LeetCode #15
    Medium
  3. 3
    3Sum Closest
    Slight Variation·LeetCode #16
    Medium
  4. 4
    Valid Triangle Number
    Medium·LeetCode #611
    Medium
  5. 5
    4Sum
    Pattern Transfer·LeetCode #18
    Medium
  6. 6
    3Sum With Multiplicity
    Tricky / Edge Case·LeetCode #923
    Medium

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?