Skip to content

Two Pointers — 3Sum Closest ​

↗ LeetCode: 3Sum Closest · Medium · pattern chapter →

Asked atMetaAmazonGoogleMicrosoft

Given an integer array nums of length n and integer target, return the sum of three integers from nums that is closest to target.

Example 1 — nums = [-1,2,1,-4], target = 1 → 2 (-1 + 2 + 1 = 2) Example 2 — nums = [0,0,0], target = 1 → 0Example 3 — nums = [1,1,1,0], target = -100 → 2

Constraints — 3 ≤ n ≤ 500; -10³ ≤ nums[i], target ≤ 10³. Brute enumerates every triple in O(n³) = 1.25·10⁸ ops at n=500 (borderline). Sort + two-pointer is O(n²) = 2.5·10⁵ ops.

Progressive Hints
Try to solve it yourself first. Reveal hints only when stuck — each hint is progressively more specific.
---
⏱️Interview timer00:00
Practice under interview pressure. Start when you begin reading; stop when you finish. Save best only when you had a full working solution.
Target for interview: Medium = 20-25 min · Hard = 30-40 min · Best time persists on this device only.

Approach 1 — Triple nested loop ​

Intuition. Enumerate every triplet; keep the sum with smallest |sum - target|.

java
int threeSumClosestBrute(int[] nums, int target) {
    int n = nums.length, best = nums[0] + nums[1] + nums[2];
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            for (int k = j + 1; k < n; k++) {
                int s = nums[i] + nums[j] + nums[k];
                if (Math.abs(s - target) < Math.abs(best - target)) best = s;
            }
    return best;
}

Complexity — Time O(n³); Space O(1).


Approach 2 — Sort + two-pointer ​

Insight from brute. Same shape as 3Sum. Sort. Fix i; two pointers on [i+1, n-1] — move whichever pointer nudges the sum toward target.

Early return. If sum exactly equals target, we can't beat it.

java
int threeSumClosest(int[] nums, int target) {
    Arrays.sort(nums);
    int n = nums.length;
    int best = nums[0] + nums[1] + nums[2];
    for (int i = 0; i < n - 2; i++) {
        int l = i + 1, r = n - 1;
        while (l < r) {
            int s = nums[i] + nums[l] + nums[r];
            if (Math.abs(s - target) < Math.abs(best - target)) best = s;
            if (s == target) return s;
            if (s < target) l++;
            else r--;
        }
    }
    return best;
}
Execution Trace
Sort + 2p — nums=[-1,2,1,-4] sorted=[-4,-1,1,2], target=1
ilr-40-111223sum = -3dist = 4best = -3
Step 1 / 4-4+-1+2=-3; distance 4

Complexity — Time O(n²); Space O(1) extra.


Try it yourself ​

Complexity summary ​

ApproachTimeSpaceInterview grade
Triple loopO(n³)O(1)baseline
Sort + two-pointerO(n²)O(1)expected optimum

When to use which ​

  • First pass — sort + two-pointer.
  • "Return triplet, not sum" → track (a, b, c) alongside best.
  • "kSum closest" → recurse: fix (k-2) values, close with 2-pointer.
  • Skip duplicates — not required for closeness (any triplet is fine), but if asked to return the first found or all tying triplets, add dedup skips.
✨AI Study CompanionBeta
Was this page helpful?

Released under MIT license.

💡 Quick shortcuts
H HintsR Run JavaA AI Help