DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

1 3

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

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay