Skip to content

Commit 1ab0bb0

Browse files
committed
[main] Added attempt for 4sum implementation, will refactor later
1 parent b5e48b0 commit 1ab0bb0

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

pythonProblems/leetcode/4sum.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
from typing import List, Union
2+
3+
# e = a + b + c + d
4+
# a = b + c + d
5+
# b = a + c + d
6+
7+
8+
## target = 4
9+
## 4 - 1 == 3, so check for pairs for 1 and 3, if both have pairs then we have a four-sum
10+
## 4 + (-1 + 2) + (2 + 1) == 4 + (1) + (3) == 4
11+
12+
13+
class Solution:
14+
15+
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
16+
pairs = []
17+
for i in range(len(nums)):
18+
for j in range(len(nums)):
19+
for k in range(len(nums)):
20+
elem_i = nums[i]
21+
elem_j = nums[j]
22+
elem_k = nums[k]
23+
diff = target - (elem_i + elem_j + elem_k)
24+
if i != j and j != k and k != i:
25+
altered_arr = nums[:]
26+
indexes = sorted([i, j, k])
27+
del altered_arr[indexes[2]]
28+
del altered_arr[indexes[1]]
29+
del altered_arr[indexes[0]]
30+
if diff in altered_arr:
31+
sorted_pair = sorted(
32+
[diff, elem_i, elem_j, elem_k])
33+
if sorted_pair not in pairs:
34+
pairs.append(sorted_pair)
35+
return pairs
36+
37+
38+
if __name__ == '__main__':
39+
nums = [2, 2, 2, 2, 2]
40+
target = 8
41+
sol = Solution()
42+
print(sol.fourSum(nums, target))
43+
44+
# def threeSum(self, nums: List[int], target: int) -> Union[List[int], None]:
45+
# for i in range(len(nums)):
46+
# result = target - nums[i]
47+
# if result in nums:
48+
# j = nums.index(result)
49+
# result = Solution.twoSum(self, nums[:j] + nums[j + 1:], result)
50+
# return [target] + result if result != None else []
51+
# return None

0 commit comments

Comments
 (0)