3Sum
Clarify the problem:
- The problem requires us to find all unique triplets in an array that add up to zero.
- We need to implement a function that takes an array of integers as input and returns a list of unique triplets that satisfy the given condition.
Analyze the problem:
- Input: An array of integers.
- Output: A list of unique triplets (lists) that add up to zero.
- Constraints:
- The length of the input array is in the range [0, 3000].
- Each integer in the array is in the range [-10^5, 10^5].
- The solution set must not contain duplicate triplets.
Design an algorithm:
- We can use a two-pointer approach to solve the problem.
- First, we sort the input array in ascending order.
- Then, we iterate through the array and for each element
nums[i], we set two pointers,leftandright, at positionsi+1andn-1, respectively, wherenis the length of the array. - While
leftis less thanright, we perform the following steps:- Calculate the sum
total = nums[i] + nums[left] + nums[right]. - If
totalis equal to zero, we have found a valid triplet. We add it to the result list. - If
totalis less than zero, we incrementleftto move towards larger values. - If
totalis greater than zero, we decrementrightto move towards smaller values. - If
totalis zero, we continue incrementingleftor decrementingrightto find the next distinct triplet.
- Calculate the sum
- We continue this process for each element in the array.
- Finally, we return the result list containing all the unique triplets.
Explain your approach:
- We will implement a function called
threeSumto solve the problem. - The function will take an array of integers,
nums, as input. - We will first check if the length of
numsis less than 3. If so, we will return an empty list. - We will sort the
numsarray in ascending order. - We will create an empty list called
resultto store the unique triplets. - We will iterate through the
numsarray up to the third-to-last element. - For each element
nums[i], we will set two pointers,leftandright, at positionsi+1andn-1, respectively, wherenis the length of the array. - While
leftis less thanright, we will calculate the sumtotal = nums[i] + nums[left] + nums[right]and perform the necessary comparisons to find the triplets. - We will handle duplicate values by skipping them using conditional checks.
- We will return the
resultlist containing all the unique triplets.
- We will implement a function called
Write clean and readable code:
pythondef threeSum(nums): if len(nums) < 3: return [] nums.sort() result = [] for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue left = i + 1 right = len(nums) - 1 while left < right: total = nums[i] + nums[left] + nums[right] if total == 0: result.append([nums[i], nums[left], nums[right]]) while left < right and nums[left] == nums[left + 1]: left += 1 while left < right and nums[right] == nums[right - 1]: right -= 1 left += 1 right -= 1 elif total < 0: left += 1 else: right -= 1 return resultTest your code:
python# Test case 1 nums = [-1, 0, 1, 2, -1, -4] # The unique triplets that add up to zero are [-1, -1, 2] and [-1, 0, 1] assert threeSum(nums) == [[-1, -1, 2], [-1, 0, 1]] # Test case 2 nums = [] # Empty input, so the output should be an empty list assert threeSum(nums) == [] # Test case 3 nums = [0, 0, 0] # The unique triplet [0, 0, 0] adds up to zero assert threeSum(nums) == [[0, 0, 0]] # Test case 4 nums = [1, 2, -2, -1] # There are no unique triplets that add up to zero assert threeSum(nums) == [] # Test case 5 nums = [1, -1, -1, 0] # The unique triplet [1, -1, 0] adds up to zero assert threeSum(nums) == [[-1, 0, 1]]We have tested the code with multiple test cases, including cases with positive, negative, and zero integers, as well as empty input. The output for each test case matches the expected results.
Optimize if necessary:
- The current solution has a time complexity of O(N^2), where N is the length of the input array.
- This is because we have nested loops to iterate through the array and find the triplets.
- The space complexity is O(N) because we use additional space to store the result list.
- The code can be further optimized by avoiding duplicate calculations and unnecessary iterations.
Handle error cases:
- The code handles the case when the input array has less than three elements and returns an empty list.
- The code assumes that the input is a valid list of integers.
Discuss complexity analysis:
- Let N be the length of the input array.
- The time complexity of the solution is O(N^2) because we have nested loops to iterate through the array and find the triplets.
- The space complexity is O(N) because we use additional space to store the result list.
- The code can be further optimized to avoid duplicate calculations and unnecessary iterations, which would reduce the constant factors in the time complexity.