2Brute2Best
🔥0

Triplet Sum in Array

Medium·GeeksforGeeksBasic Anchor
GeeksforGeeks
30-Second Mental ModelTwo Pointers (fix one + opposite ends)
Complexity:O(N³)→O(N²)
Key Insight

Sort the array. Fix arr[i] as the smallest element of the triplet. In the part to its right, put left at the start and right at the end. If arr[left] + arr[right] is smaller than need, move left right to get a bigger sum. If it is bigger, move right left. If it equals need, we found a triplet.

Core Validity Invariant

For a fixed i, a pair (left, right) is the answer when arr[left] + arr[right] == need. Because the range is sorted, a sum that is too small means arr[left] is useless, and a sum that is too big means arr[right] is useless.

01

Problem

You are given an array of integers arr and a number target.

Can you pick three elements at three different positions whose sum is exactly target? Return true if such a triplet exists, otherwise false.

The same position can't be used twice, but two positions may hold the same value.

Input

An integer array arr of length n, and an integer target.

Output

true if some arr[i] + arr[j] + arr[k] == target with i, j, k all different, else false. (Function: bool hasTripletSum(vector<int>& arr, int target).)

Example 1
Input: arr = [1, 4, 45, 6, 10, 8], target = 13
Output: true

1 + 4 + 8 = 13.

Example 2
Input: arr = [1, 2, 4, 3, 6, 7], target = 10
Output: true

Several triplets work, for example 1 + 3 + 6 and 1 + 2 + 7. We only need to say that one exists.

Example 3
Input: arr = [40, 20, 10, 3, 6, 7], target = 24
Output: false

No three of these numbers add up to 24.

Constraints
  • • 3 ≤ n ≤ 10^3
  • • 1 ≤ arr[i] ≤ 10^5
  • • 1 ≤ target ≤ 3·10^5
02

First, think yourself

Before opening any solution, try to answer these on paper. Use hints only when stuck — each hint is counted.

  1. 1.

    Does the order of the elements matter for the answer, or only which three I pick?

  2. 2.

    If I already decided what the first number is, what is left to solve?

  3. 3.

    Have I solved a "find two numbers with a given sum" problem before? What did it need?

  4. 4.

    Would sorting the array change the answer? Would it make anything easier?

  5. 5.

    Can I return as soon as I find one triplet, or do I need all of them?

03

Brute force approach

04

Better approach

05

Optimized approach

06

Why does this algorithm work?

07

Dry run

08

All approaches compared

ApproachIdeaTimeSpace
Brute ForceThree nested loops over i < j < kO(N³)O(1)
BetterFix arr[i]; find a pair summing to target − arr[i] using a setO(N²)O(N)
OptimalSort; fix arr[i]; move left/right inwards to find the pairO(N²)O(1)
09

Why does this belong to this pattern?

Clues in the problem statement
  • “three elements”Three unknowns → fix one of them in a loop, leaving a pair problem.
  • “sum equal to target”A pair with a known sum → Two Sum. In a sorted array that is opposite-ends two pointers.
  • “return true / false”Order and positions don't matter for the answer → we are free to sort.
Pick 3 elements+fixed target sum+order doesn't matter (sorting allowed)→Two Pointers (fix one + opposite ends)

This is the anchor of the k-sum family. The one idea to take away: fix one element, and the rest is Two Sum II on the part to its right. Here we only need yes/no, so there is nothing to deduplicate. The next questions keep this exact loop and add one thing each: collecting every unique triplet (3Sum), tracking the closest sum (3Sum Closest), counting instead of finding (Valid Triangle Number), fixing two elements (4Sum), and counting with repeated values (3Sum With Multiplicity).

10

Don't make this mistake

Pattern confusion: treating every "pair sum" problem as two pointers

Two pointers works here because we only return true/false, so sorting is harmless. Plain Two Sum (LC 1) asks for the indices of the pair in an unsorted array. Sorting would scramble those indices, so Two Sum is a hash-map problem, not a two-pointer one. Before sorting, always ask: does the answer depend on the original positions?

Using the fixed element twice
✗ int left = 0, right = n - 1;
✓ int left = i + 1, right = n - 1;

If left starts at 0, it can land on i itself, so arr[i] gets counted twice. For arr = [2, 5, 9], target = 9, fixing 2 needs a pair summing to 7, and left = 0 finds 2 + 5 — so it wrongly answers true using the same 2 twice. Searching only to the right of i also avoids checking the same triplet in a different order.

Forgetting to sort

The pointer moves are only safe in a sorted array. Without sorting, sum < need tells you nothing about which element to drop, and the search silently misses triplets.

Allowing left == right
✗ while (left <= right)
✓ while (left < right)

When left == right both pointers sit on one element. Adding it to itself uses one position twice, which the problem does not allow.

11

Want to implement this?

Write it yourself on GeeksforGeeks, then come back and compare your code with the solutions above.

Open coding workspace
How did it go?
Beyond The LeetCode Problem

How this concept connects to System Design & C++ Systems

Bridge DSA with production engineering

Top engineering interviews test whether you understand how algorithms like Two Pointers translate into production architectures and low-level memory mechanics.