Python Short N Simple


  • 0

    We just need to check for duplicates when the previous triplet summed to 0. Other duplicates will be skipped over anyway as we're moving the low and high pointers according to the relative position of our current sum to the target sum (0).

        def threeSum(self, nums):
    
            nums.sort()
            res = []
            for i in range(len(nums)-2):
                if i == 0 or nums[i] != nums[i-1]: # skip if same value as the previous pivot.
                    l, h = i + 1, len(nums)-1
                    while l < h:
                        s = nums[i] + nums[l] + nums[h] # calculate sum of current triplet
                        if s >= 0: 
                            # check if current val is different from prev
                            if s == 0 and (h == len(nums)-1 or nums[h] != nums[h+1]):
                                res.append([nums[i],nums[l],nums[h]])
                            h -= 1 # move down high ptr
                        else:
                            l += 1 # move up low ptr
            return res
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.