
Problem
Solution
Submissions
Three Sum
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to find all unique triplets in an array that sum to zero. Given an array of integers, 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 set must not contain duplicate triplets.
Example 1
- Input: nums = [-1, 0, 1, 2, -1, -4]
- Output: [[-1, -1, 2], [-1, 0, 1]]
- Explanation:
- The array contains numbers [-1, 0, 1, 2, -1, -4].
- We need to find triplets that sum to zero.
- First triplet: -1 + (-1) + 2 = 0.
- Second triplet: -1 + 0 + 1 = 0.
- These are the only unique triplets that sum to zero.
- The array contains numbers [-1, 0, 1, 2, -1, -4].
Example 2
- Input: nums = [0, 1, 1]
- Output: []
- Explanation:
- The array contains numbers [0, 1, 1].
- We check all possible triplets.
- The only triplet is 0 + 1 + 1 = 2.
- Since 2 ≠ 0, there are no valid triplets.
- Return empty array.
- The array contains numbers [0, 1, 1].
Constraints
- 3 ≤ nums.length ≤ 3000
- -10^5 ≤ nums[i] ≤ 10^5
- The solution set must not contain duplicate triplets
- Time Complexity: O(n^2)
- Space Complexity: O(1) excluding the output array
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Sort the array first to handle duplicates easily and use two-pointer technique
- Use a fixed pointer for the first element and two pointers for the remaining elements
- Skip duplicate elements to avoid duplicate triplets in the result
- Use two-pointer approach to find pairs that sum to the negative of the first element
- Move pointers based on the current sum compared to the target