Skip to content

Commit b94cdba

Browse files
add find triplets with 0 sum (3sum) (TheAlgorithms#10040)
* add find triplets with 0 sum (3sum) * Update find_triplets_with_0_sum.py * Update find_triplets_with_0_sum.py --------- Co-authored-by: Christian Clauss <[email protected]>
1 parent ecf21bf commit b94cdba

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from itertools import combinations
2+
3+
4+
def find_triplets_with_0_sum(nums: list[int]) -> list[list[int]]:
5+
"""
6+
Given a list of integers, return elements a, b, c such that a + b + c = 0.
7+
Args:
8+
nums: list of integers
9+
Returns:
10+
list of lists of integers where sum(each_list) == 0
11+
Examples:
12+
>>> find_triplets_with_0_sum([-1, 0, 1, 2, -1, -4])
13+
[[-1, -1, 2], [-1, 0, 1]]
14+
>>> find_triplets_with_0_sum([])
15+
[]
16+
>>> find_triplets_with_0_sum([0, 0, 0])
17+
[[0, 0, 0]]
18+
>>> find_triplets_with_0_sum([1, 2, 3, 0, -1, -2, -3])
19+
[[-3, 0, 3], [-3, 1, 2], [-2, -1, 3], [-2, 0, 2], [-1, 0, 1]]
20+
"""
21+
return [
22+
list(x)
23+
for x in sorted({abc for abc in combinations(sorted(nums), 3) if not sum(abc)})
24+
]

0 commit comments

Comments
 (0)