Tutorialspoint
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.
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.
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
ArraysShopifyD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Sort the input array to enable two-pointer technique and handle duplicates easily.
 Step 2: Use a fixed pointer for the first element and iterate through the array.
 Step 3: For each fixed element, use two pointers (left and right) to find pairs that sum to negative of the fixed element.
 Step 4: Skip duplicate elements to avoid duplicate triplets in the result set.
 Step 5: Move the left pointer right if sum is less than zero, move right pointer left if sum is greater than zero.
 Step 6: When sum equals zero, add the triplet to result and move both pointers while skipping duplicates.
 Step 7: Return the final result array containing all unique triplets.

Submitted Code :