wip: 3 pointers 3sum

This commit is contained in:
yigid balaban 2024-09-11 22:19:50 +03:00
parent f52b64ba4f
commit 5f98d05a8e
Signed by: fyb
GPG Key ID: E21FEB2C244CB7EB

33
medium/3sum.py Normal file
View File

@ -0,0 +1,33 @@
#!/usr/bin/python
# yigid balaban <fyb@fybx.dev>
# neetcode 2024
# 3sum
def solution(nums: list[int]) -> list[list[int]]:
if len(nums) < 3:
return []
if len(nums) == 3 and sum(nums) == 0:
return [nums]
nums = sorted(nums)
triples = []
def comb(what: list[int], head: int):
mtriples = []
for p0 in range(0, len(what) + 1):
for p1 in range(p0, len(what)):
if p1 != p0 and head + what[p0] + what[p1] == 0:
triple = sorted([head, what[p0], what[p1]])
if triple not in triples and triple not in mtriples:
mtriples.append(triple)
return mtriples
for p in range(len(nums) - 3):
triples.extend(comb(nums[p + 1:], nums[p]))
return triples
print(solution([0,0]) == [])
print(solution([-1,0,1,2,-1,-4]), solution([-1,0,1,2,-1,-4]) == [[-1,-1,2],[-1,0,1]])
print(solution([0,1,1]) == [])
print(solution([0,0,0]) == [[0,0,0]])
print(solution([0,0,0,0]) == [[0,0,0]])