-2

Here's the Problem Statement:

Given an array nums of n integers, 
are there elements a, b, c in nums such  that a + b + c = 0? 
Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[[-1, 0, 1],[-1, -1, 2]]

I'm solving Leetcode 3Sum problem right now and getting Time Limit Exceeded error for the below Code:

class Solution:
def threeSum(self, nums):
    triplets=[]
    nums.sort()
    for i in range(len(nums)-1):
        l=i+1
        r=len(nums)-1
        while l<r:
            sum=nums[i]+nums[l]+nums[r]
            if sum==0:
                if not [nums[i],nums[l],nums[r]] in triplets:
                    triplets+=[[nums[i],nums[l],nums[r]]]
            if sum<0:
                l+=1
            else:
                r-=1
    return triplets

Can anyone tell me where can I optimize this code?

MBo
  • 77,366
  • 5
  • 53
  • 86
Parth S.
  • 63
  • 1
  • 9

2 Answers2

1

Your algorithm looks optimal in general (slightly better complexity exists but approach perhaps is too complex for practical purposes).

But seems that searching of sublist in list is rather slow operation (probably linear for unsorted)

Use dictionary instead and extract triplets at the end.

MBo
  • 77,366
  • 5
  • 53
  • 86
1
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        result = []
        N = len(nums)
        for i in range(N):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            target = -nums[i]
            l = i + 1
            r = N - 1
            while l < r:
                if nums[l] + nums[r] == target:
                    result.append([nums[l],nums[r],nums[i]])
                    l = l + 1
                    while l <= r and nums[l] == nums[l - 1]:
                        l = l + 1
                elif nums[l] + nums[r] > target:
                    r = r - 1
                else:
                    l = l + 1
        return result
uday reddy
  • 464
  • 5
  • 7