19. 3Sum
mediumAsked at SquareFind every trio of transaction adjustments in a ledger that net to zero — Square's reconciliation engine flags three-way payment splits that cancel out, which can signal money-laundering patterns in its fraud-detection pipeline.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums, return all triplets [nums[i], nums[j], nums[k]] such that i, j, and k are distinct indices and nums[i] + nums[j] + nums[k] == 0. The solution set must not contain duplicate triplets.
Constraints
3 <= nums.length <= 3000-10^5 <= nums[i] <= 10^5
Examples
Example 1
nums = [-1,0,1,2,-1,-4][[-1,-1,2],[-1,0,1]]Example 2
nums = [0,1,1][]Example 3
nums = [0,0,0][[0,0,0]]Approaches
1. Brute force
Check all O(n^3) triplets; deduplicate with a set. Times out on large inputs.
- Time
- O(n^3)
- Space
- O(n)
function threeSum(nums) {
const res = new Set();
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
for (let k = j + 1; k < nums.length; k++) {
if (nums[i] + nums[j] + nums[k] === 0) {
const trip = [nums[i], nums[j], nums[k]].sort((a, b) => a - b);
res.add(JSON.stringify(trip));
}
}
}
}
return [...res].map(JSON.parse);
}Tradeoff:
2. Sort + two pointers
Sort the array, then for each element use two pointers to find complementary pairs. Skip duplicates by advancing pointers past repeated values. O(n^2) time, no hash set needed.
- Time
- O(n^2)
- Space
- O(n)
function threeSum(nums) {
nums.sort((a, b) => a - b);
const res = [];
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
let lo = i + 1, hi = nums.length - 1;
while (lo < hi) {
const sum = nums[i] + nums[lo] + nums[hi];
if (sum === 0) {
res.push([nums[i], nums[lo], nums[hi]]);
while (lo < hi && nums[lo] === nums[lo + 1]) lo++;
while (lo < hi && nums[hi] === nums[hi - 1]) hi--;
lo++; hi--;
} else if (sum < 0) lo++;
else hi--;
}
}
return res;
}Tradeoff:
Square-specific tips
Square's fraud team works with signed integer ledger deltas daily, so they expect you to reason about the duplicate-skip logic under pressure. Trace through [-1,-1,0,1,2] on the whiteboard and show exactly which pointer moves skip the second -1 — that real-data trace is what separates candidates who memorized the pattern from those who own it.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill 3Sum and other Square interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →