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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay