Leetcode 3Sum problem solution in Python programming

In the Leetcode 3Sum problem solution in Python programming 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.

Leetcode 3Sum problem solution in Python programming

class Solution(object):
    def threeSum(self, nums):
        nums.sort()
        ans=set()
        for i in range(len(nums)):
            target=-nums[i]
            start=i+1
            end=len(nums)-1
            while(start<end):
                summ=nums[start]+nums[end]
                if summ<target:
                    start+=1
                elif summ>target:
                    end-=1
                else:
                    ans.add((nums[i],nums[start],nums[end]))
                    start+=1
                    end-=1
        return ans

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *