Tutorialspoint
Problem
Solution
Submissions

3Sum

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C program to find all unique triplets in an array which gives the sum of zero. Given an array of integers, your function should return all possible triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, j != k, and nums[i] + nums[j] + nums[k] == 0.

Example 1
  • Input: nums = [-1, 0, 1, 2, -1, -4]
  • Output: [[-1, -1, 2], [-1, 0, 1]]
  • Explanation:
    • Sort the array to get [-4, -1, -1, 0, 1, 2].
    • For the first element -1 (at index 1), we find pairs (0, 1) at indices 3 and 4, giving (-1, 0, 1).
    • For the first element -1 (at index 2), we find pair (-1, 2) at indices 1 and 5, giving (-1, -1, 2).
    • Select only unique triplets only, we have [-1, -1, 2] and [-1, 0, 1].
Example 2
  • Input: nums = [0, 0, 0]
  • Output: [[0, 0, 0]]
  • Explanation: The only possible triplet is [0, 0, 0], which sums to 0.
Constraints
  • 3 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5
  • The solution set must not contain duplicate triplets
  • Time Complexity: O(n²)
  • Space Complexity: O(n) or O(1) excluding the output array
ArraysNumberGoldman SachsApple
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 make it easier to handle duplicates and to use the two-pointer technique
  • Use a for loop to fix the first element of the triplet
  • For each first element, use the two-pointer technique to find pairs that sum to the negative of the first element
  • Skip duplicate values to avoid duplicate triplets
  • Ensure the indices i, j, and k are distinct

Steps to solve by this approach:

 Step 1: Sort the input array to handle duplicates efficiently and to use the two-pointer technique.
 Step 2: Iterate through the array with a loop to fix the first element of the triplet.
 Step 3: For each first element, use two pointers (left starting after the first element and right at the end) to find pairs that sum to the negative of the first element.
 Step 4: Skip duplicate values for all three elements to avoid duplicate triplets in the result.
 Step 5: When a valid triplet is found, add it to the result and move both pointers.
 Step 6: If the sum is less than zero, move the left pointer to increase the sum; if greater than zero, move the right pointer to decrease the sum.
 Step 7: Properly manage memory allocation and deallocation for the result array and column sizes.

Submitted Code :