imashutosh51

4 Sum

Feb 5th, 2026 (edited)
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. '''
  2. Use two for loops for 2 elements and then iterate the rest of the array using two pointer, and once the target matches,push it into the ans.second loop should start after the first one ends.
  3.  
  4. Trick:
  5. Skip the continous duplicates on all the 4 pointers, i,j,l,r
  6. '''
  7. class Solution:
  8.     def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
  9.         # ans=set()
  10.         nums.sort()
  11.         ans=[]
  12.         for i in range(len(nums)):
  13.             if i>0 and nums[i]==nums[i-1]: #skip the continous duplicates as one appearance for each number
  14.                 continue
  15.             for j in range(i+1,len(nums)):
  16.                 if j>i+1 and nums[j]==nums[j-1]: #skip the continous duplicates as one appearance for each number but it has to skip the previous jth element, not the previous ith element(2,2,2,2) os j>i+1
  17.                     continue
  18.                 l=j+1
  19.                 r=len(nums)-1
  20.                 while l<r:
  21.                     if nums[l]+nums[r]+nums[i]+nums[j]==target:
  22.                         ans.append((nums[i],nums[j],nums[l],nums[r]))  
  23.                         l+=1
  24.                         r-=1
  25.                         while l<r and nums[l]==nums[l-1]: #skip the continous duplicates as one appearance for each number
  26.                             l+=1
  27.                         while r>l and nums[r]==nums[r+1]: #skip the continous duplicates as one appearance for each number
  28.                             r-=1
  29.                     elif nums[l]+nums[r]+nums[i]+nums[j]>target:
  30.                             r-=1
  31.                     else:
  32.                         l+=1
  33.                        
  34.         return ans
  35.  
  36.  
  37.  
  38.        
Advertisement
Add Comment
Please, Sign In to add comment