Triplet Sum (3Sum)
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
Question
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. The solution must not contain any duplicate triplets, and the order of numbers in the triplet must be in ascending order.

For example, consider the following array,
nums = [-2, 1, -3, 5, -3, 5]
If we look closely, there are a lot of duplicate elements here. The unique triplet that gives the sum as 0 is [-3, -2, 5]. This triplet can be formed from numbers at indices 0, 2, and 3. It can also be formed from numbers at indices 0, 4, and 5. Since we are avoiding duplicates, we consider only one unique triplet to be the correct solution, regardless of the indices.
Constraints
- 3 <=
nums.length<= 3000 - 105 <=
nums[i]<= 105
CONTINUE WITH ALGODAILY PREMIUM
Keep going with the complete tutorial.
Unlock the remaining explanations and exercises, alongside the full learning library.
Explore Premium →