Advertisement
imashutosh51

3Sum

Oct 6th, 2022 (edited)
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. /*
  2. Logic:one loop on whole array for one elemnt of triplet and other two element will be found by two-pointer.
  3. */
  4.  
  5. class Solution:
  6.     def threeSum(self, nums: List[int]) -> List[List[int]]:
  7.         nums.sort()
  8.         ans=[]
  9.         for i in range(len(nums)):
  10.             if i>0 and nums[i]==nums[i-1]:
  11.                 continue
  12.             j=i+1
  13.             k=len(nums)-1
  14.             while j<k:
  15.                 if nums[i]+nums[j]+nums[k]==0:
  16.                     ans.append([nums[i],nums[j],nums[k]])
  17.                     j+=1
  18.                     k-=1
  19.                     while j<k and nums[j]==nums[j-1]: #These two while is there if suppose 1M 0 is there in array
  20.                         j+=1
  21.                     while k>j and nums[k]==nums[k+1]:
  22.                         k-=1
  23.                 elif nums[i]+nums[j]+nums[k]>0:
  24.                     k-=1
  25.                 else:
  26.                     j+=1
  27.         return ans
  28.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement