DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

LeetCode "4Sum"

3Sum Closest was helpful.
This code is slow😕

4Sum

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:

        nums.sort()
        len_nums = len(nums)
        result = set()

        for i in range(len_nums - 3):
            for j in range(i + 1, len_nums - 2):

                left = j + 1
                right = len_nums - 1                
                while left < right:

                    sum_nums = nums[i] + nums[j] + nums[left] + nums[right]
                    if sum_nums == target:
                        result.add((nums[i], nums[j], nums[left], nums[right]))
                        left += 1
                    else:
                        if sum_nums < target:
                            left += 1
                        else:
                            right -= 1

        return result
Enter fullscreen mode Exit fullscreen mode

Top comments (0)