def test(fn):
= [-1,0,1,2,-1,-4]
nums = [[-1,-1,2],[-1,0,1]]
expected assert fn(nums) == expected
= [0,1,1]
nums = []
expected assert fn(nums) == expected
= [0,0,0]
nums = [[0,0,0]]
expected assert fn(nums) == expected
Problem Source: Leetcode
Problem Description
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.
tests
Solution
This solution builds on Two Sum II - Input Array is Sorted. If this solution is confusing, revisit it after understanding that proble,
- Time Complexity:
O(1)
- Space Complexity:
O(nlogn)
from typing import List
def threeSum(nums: List[int]) -> List[List[int]]:
nums.sort()= []
res
for i in range(len(nums)):
if i>0 and nums[i] == nums[i-1]: continue
= i+1, len(nums)-1
l,r while l < r:
= nums[i] + nums[l] + nums[r]
curr_sum
#Two Sum on sorted list
if curr_sum < 0: # If too small
+= 1 # make it bigger
l elif curr_sum > 0: # If too big
-= 1 # make it smaller
r else:
res.append([nums[i],nums[l],nums[r]])+= 1 # move to next
l while nums[l] == nums[l - 1] and l < r:
+= 1 # keep incrementing if dupes
l return res
test(threeSum)