15. 3Sum
Asked at 48Bloomberg80Amazon79Microsoft75Google73Meta72Apple59Walmart Labs79tcs73Accenture66Infosys66Wissen Technology100Works Applications100Visa91Wix87Roku87Adobe86Cloudflare79Qualcomm76Nutanix71Vimeo71Zoho70Autodesk69Agoda69AMD69Tesla68TikTok68Dream1168Morgan Stanley64PhonePe64Oracle64Myntra64Samsung63EPAM Systems60IBM59Deloitte59Coupang58Meesho57Turing55Nvidia55eBay53Flipkart52Cisco51Rubrik50ByteDance50Cognizant48Goldman Sachs42PayPal42Salesforce41
Problem
Return every distinct triplet [a, b, c] of values from nums, taken from three different positions, with a + b + c = 0. The answer must not contain duplicate triplets; order doesn't matter.
Example: [-1,0,1,2,-1,-4] → [[-1,-1,2],[-1,0,1]]
Constraints: 3 ≤ n ≤ 3000.
Sort. Fix nums[i], then run Two Sum II on the suffix for -nums[i]. Skip equal neighbours (for i and after a hit) to avoid duplicate triplets. Stop early when nums[i] > 0.
sorted: [-4, -1, -1, 0, 1, 2]
i=-1: l=-1 ............ r=2 -1+(-1)+2 = 0 ✓ -> [-1,-1,2]
l=0 ......r=1 -1+0+1 = 0 ✓ -> [-1,0,1]
i=-1 (dup) skip
Complexity: O(n²) time, O(1) extra (besides sort).
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
for i in range(len(nums) - 2):
if nums[i] > 0:
break
if i and nums[i] == nums[i - 1]:
continue
l, r = i + 1, len(nums) - 1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s < 0:
l += 1
elif s > 0:
r -= 1
else:
res.append([nums[i], nums[l], nums[r]])
l += 1
while l < r and nums[l] == nums[l - 1]:
l += 1
r -= 1
return res
assert sorted(map(sorted, Solution().threeSum([-1, 0, 1, 2, -1, -4]))) == sorted(map(sorted, [[-1, -1, 2], [-1, 0, 1]]))
assert sorted(map(sorted, Solution().threeSum([0, 0, 0]))) == sorted(map(sorted, [[0, 0, 0]]))
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length - 2 && nums[i] <= 0; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int l = i + 1, r = nums.length - 1;
while (l < r) {
int s = nums[i] + nums[l] + nums[r];
if (s < 0) l++;
else if (s > 0) r--;
else {
res.add(Arrays.asList(nums[i], nums[l], nums[r]));
l++;
while (l < r && nums[l] == nums[l - 1]) l++;
r--;
}
}
}
return res;
}
}
func threeSum(nums []int) [][]int {
sort.Ints(nums)
res := [][]int{}
for i := 0; i < len(nums)-2 && nums[i] <= 0; i++ {
if i > 0 && nums[i] == nums[i-1] {
continue // same first number, same triples
}
for l, r := i+1, len(nums)-1; l < r; {
s := nums[i] + nums[l] + nums[r]
switch {
case s < 0:
l++
case s > 0:
r--
default:
res = append(res, []int{nums[i], nums[l], nums[r]})
l++
for l < r && nums[l] == nums[l-1] {
l++
}
r--
}
}
}
return res
}