MediumArraysAI interview only
3Sum
Asked atgoogleamazonmetamicrosoftbloombergapple
01 · Problem
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
02 · Examples
Example 01
Input
nums = [-1,0,1,2,-1,-4]
Output
[[-1,-1,2],[-1,0,1]]
The distinct triplets that sum to 0 are [-1,-1,2] and [-1,0,1].
Example 02
Input
nums = [0,1,1]
Output
[]
No three numbers sum to 0.
Example 03
Input
nums = [0,0,0]
Output
[[0,0,0]]
The only possible triplet is [0,0,0] which sums to 0.
03 · Constraints
- 013 <= nums.length <= 3000
- 02-105 <= nums[i] <= 105
04 · Optimal complexity
- Time
- O(n²)
- Space
- O(1)
05 · Two ways to work on it
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.