imashutosh51

3Sum

Oct 6th, 2022 (edited)
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. /*
  2. Logic:sort the array first and then 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, arr: List[int]) -> List[List[int]]:
  7.         arr.sort()
  8.         ans=set()
  9.         for k in range(len(arr)):
  10.             if k > 0 and arr[k] == arr[k-1]:   # skip duplicate k
  11.                 continue
  12.  
  13.             i,j=k+1,len(arr)-1
  14.             while i<j: #no need to check i!=k or j!=k because i start after k and i never gonna reach j
  15.                 # i+=1 if k==i else j-=1
  16.                 if arr[k]+arr[i]+arr[j]==0:
  17.                     t=(arr[k],arr[i],arr[j])# (k,i,j) always increasing bcz k come first then i & j as pointer on both side
  18.                     ans.add(t)
  19.                     i+=1
  20.                     j-=1
  21.  
  22.                     while i < j and arr[i] == arr[i-1]:   # skip duplicate i
  23.                         i += 1
  24.                     while i < j and arr[j] == arr[j+1]:   # skip duplicate j
  25.                         j -= 1
  26.  
  27.                 elif arr[k]+arr[i]+arr[j]>0:
  28.                     j-=1
  29.                 else:
  30.                     i+=1
  31.  
  32.         return [list(x) for x in ans]
  33.  
  34.  
Advertisement
Add Comment
Please, Sign In to add comment