4 sum Problem

 class Solution:

  def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        # sort the array
        nums.sort()
        res = []
        n = len(nums)
        for i in range(n):
            # avoid duplicate
            if i > 0 and nums[i] == nums[i-1]:
                continue
            for j in range(i+1,n):
                if j > i + 1 and nums[j] == nums[j-1]:
                    continue
               
                left = j+1
                right = n-1
                while left < right:
                    total = nums[i]+ nums[j]+ nums[left]+ nums[right]

                    if total == target:
                        res.append([nums[i], nums[j], nums[left], nums[right]])
                        # Skip Duplicate
                        while left < right and nums[left] == nums[left + 1]:
                            left += 1
                        while left < right and nums[right] == nums[right - 1]:
                            right -= 1
                        left += 1
                        right -= 1
                    elif total < target:
                        left += 1
                    else:
                        right -= 1

        return res
               

           

Comments

Popular posts from this blog

3 Sum Problem Leetcode

best-time-to-buy-and-sell-stock

Staircase Algorithm