From 813d8e0ccc16853b5b6e0b330d908ab35c311d1a Mon Sep 17 00:00:00 2001 From: Sangeeth Sudheer Date: Fri, 1 Apr 2022 23:56:39 +0530 Subject: [PATCH] feat(18-4sum): add py3 solution --- 0018_4sum/README.md | 21 ++++++++++++++++++ 0018_4sum/python3/solution.py | 41 +++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 0018_4sum/README.md create mode 100644 0018_4sum/python3/solution.py diff --git a/0018_4sum/README.md b/0018_4sum/README.md new file mode 100644 index 0000000..bac4702 --- /dev/null +++ b/0018_4sum/README.md @@ -0,0 +1,21 @@ +Given an array `nums` of `n` integers, return _an array of all the unique quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that: + +* `0 <= a, b, c, d < n` +* `a`, `b`, `c`, and `d` are distinct. +* `nums[a] + nums[b] + nums[c] + nums[d] == target` + +You may return the answer in any order. + +Example 1: + + Input: nums = [1,0,-1,0,-2,2], target = 0 Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] + +Example 2: + + Input: nums = [2,2,2,2,2], target = 8 Output: [[2,2,2,2]] + +Constraints: + +* `1 <= nums.length <= 200` +* `-109 <= nums[i] <= 109` +* `-109 <= target <= 109` diff --git a/0018_4sum/python3/solution.py b/0018_4sum/python3/solution.py new file mode 100644 index 0000000..ece326f --- /dev/null +++ b/0018_4sum/python3/solution.py @@ -0,0 +1,41 @@ +# NOTE: Far from the most optimal solution to the problem. +# Time complexity: O(n^3) +# Space complexity: O(n^2) // NOTE: Really? And how? +class Solution: + def fourSum(self, nums: List[int], target: int) -> List[List[int]]: + arr_len = len(nums) + + # Helps keep out duplicates + nums.sort() + + # Will be a dict with each key storing a `set` of 2-tuples (pair of nums) + diff_cache = {} + + quadruplets = set() + + # No point in iterating with the last element since we won't be adding + # any new quadruplets at that point + for i in range(1, arr_len - 1): + for j in range(i + 1, arr_len): + current_sum = nums[i] + nums[j] + difference = target - current_sum + + if difference in diff_cache: + # diff_cache could have multiple pairs that add up to the same + # `difference`. We need to form quadruplets with all of them + # and store them in `quadruplets` + for pair in diff_cache[difference]: + quadruplets.add(pair + (nums[i], nums[j])) + + # Compute sum with every element to the left of i and store + # in diff_cache. We do this at this later point to avoid duplicates + for k in range(0, i): + current_sum = nums[i] + nums[k] + + if current_sum in diff_cache: + diff_cache[current_sum].add((nums[i], nums[k])) + else: + # This has to be a set to avoid duplicates + diff_cache[current_sum] = { (nums[i], nums[k]) } + + return quadruplets