3Sum - Complete Solution Guide
3Sum is LeetCode problem 15, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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. Example 1: Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1
Detailed Explanation
The 3Sum problem requires us to find all unique triplets (sets of three numbers) within a given array of integers that sum up to zero. The triplets must consist of three distinct elements from the array, meaning the indices of the three numbers must be different. The solution should return a list of these unique triplets. Duplicate triplets should not be included in the result.
Solution Approach
The solution uses a combination of sorting and the two-pointer technique to efficiently find the triplets. First, the input array is sorted in ascending order. This allows for a linear traversal of the array, with two pointers (left and right) positioned to find the remaining two numbers that, when combined with the current element, sum to zero. After sorting, the algorithm iterates through the array. For each element, two pointers are initialized: 'left' starts at the next element after the current element, and 'right' starts at the end of the array. The algorithm then moves the left and right pointers towards each other, adjusting their positions based on whether the current sum is less than, greater than, or equal to zero. Duplicate triplets are avoided by skipping over duplicate numbers while moving the pointers.
Step-by-Step Algorithm
- Step 1: Sort the input array `nums` in ascending order.
- Step 2: Iterate through the sorted array from index `i = 0` to `n - 2`, where `n` is the length of the array.
- Step 3: Inside the outer loop, check if the current number `nums[i]` is greater than 0. If it is, break the loop because all subsequent numbers will also be positive, making it impossible to find a triplet that sums to zero.
- Step 4: Check for duplicate numbers for `nums[i]`. If `i > 0` and `nums[i] == nums[i - 1]`, skip the current iteration to avoid duplicate triplets.
- Step 5: Initialize two pointers: `left = i + 1` and `right = n - 1`.
- Step 6: While `left < right`, calculate the current sum `current_sum = nums[i] + nums[left] + nums[right]`.
- Step 7: If `current_sum < 0`, increment the `left` pointer to increase the sum.
- Step 8: If `current_sum > 0`, decrement the `right` pointer to decrease the sum.
- Step 9: If `current_sum == 0`, add the triplet `[nums[i], nums[left], nums[right]]` to the result list.
- Step 10: Increment `left` and decrement `right` to find other possible triplets. Also skip duplicate numbers for `left` and `right` pointers to avoid duplicate triplets.
- Step 11: Repeat steps 6-10 until `left >= right`.
- Step 12: Return the list of unique triplets.
Key Insights
- Insight 1: Sorting the input array enables the use of the two-pointer technique to efficiently find pairs that sum to a specific target value.
- Insight 2: Skipping duplicate numbers after sorting is crucial to avoid including duplicate triplets in the final result. This is done by checking for equality with the previous element.
- Insight 3: The first number in the triplet can determine when to stop searching. If it is greater than zero, there's no possibility of finding a triplet that sums to zero because the array is sorted.
Complexity Analysis
Time Complexity: O(n^2)
Space Complexity: O(1)
Topics
This problem involves: Array, Two Pointers, Sorting.
Companies
Asked at: AMD, Accenture, Adobe, Agoda, Altimetrik, Amazon, American Express, Apple, Atlassian, Autodesk, BNY Mellon, Barclays, Bloomberg, Bosch, Cadence, Careem, Cisco, Citadel, Cloudflare, Cognizant, Docusign, Dream11, EPAM Systems, Flipkart, Gojek, Goldman Sachs, HCL, HashedIn, Infosys, Intuit, Meta, Microsoft, Morgan Stanley, Myntra, Nutanix, Nvidia, Oracle, PayPal, Paytm, Rakuten, Salesforce, Samsung, ServiceNow, Siemens, Sprinklr, Tesla, TikTok, Trexquant, Turing, Uber, Vimeo, Visa, Walmart Labs, Warnermedia, Wells Fargo, Wix, Works Applications, Yahoo, Yandex, Zoho, Zomato, Zopsmart, smartnews, tcs.