4Sum LeetCode solution in Python

1
class Solution:
2
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
3

4
if len(nums) < 4:
5
return []
6

7
nums.sort()
8
res = []
9

10
for i in range(len(nums)):
11
for j in range(i + 1, len(nums)):
12
l = j + 1
13
r = len(nums) - 1
14
while l < r:
15

16
sum_ = nums[i] + nums[j] + nums[l] + nums[r]
17
a = [nums[i], nums[j], nums[l], nums[r]]
18

19
if sum_ == target and a not in res:
20
res.append(a)
21

22
if sum_ > target:
23
r -= 1
24

25
else:
26
l += 1
27
while l < r and nums[l - 1] == nums[l]:
28
l += 1
29

30
return res
31

32
# An Upvote will be encouraging

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0