#๐Ÿ”’ optimizing leetcode #18, 4sum

4 messages ยท Page 1 of 1 (latest)

runic sundial
#
class Solution:
    def fourSum(self, nums, target):
        nums.sort()
        results = []

        for i, num in enumerate(nums):
            for j, num2 in enumerate(nums):
                if i == j:
                    continue
                else:
                    start = num + num2

                    left = 0
                    right = len(nums) - 1
                    
                    while left < right:
                        if left == i or left == j:
                            left += 1
                            continue
                        if right == i or right == j:
                            right -= 1
                            continue

                        total = start + nums[right] + nums[left]
                        if total == target:
                            result = [num, num2, nums[right], nums[left]]
                            result.sort()
                            if result not in results:
                                results.append(result)
                            right -= 1
                            left += 1
                        elif total > target:  # maker smaller
                            right -= 1
                        elif total < target:  # make bigger
                            left += 1
        return results

I feel like this makes sense to me (just one more loop over 3sum) but my result always gets scrambled up and this overall is O(N^3) which obviously isn't ideal
I realize i could go online and look at solutions-- but i'd rather keep working here iteratively until I get it fr

frail pulsarBOT
#

@runic sundial

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

frail pulsarBOT
#

@runic sundial

Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.