From b94cdbab1a7f3793e63526cd29a8f415ff0b55ac Mon Sep 17 00:00:00 2001 From: Pranavkumar Mallela <87595299+pranav-mallela@users.noreply.github.com> Date: Fri, 13 Oct 2023 01:21:53 +0530 Subject: [PATCH] add find triplets with 0 sum (3sum) (#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 --- .../arrays/find_triplets_with_0_sum.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 data_structures/arrays/find_triplets_with_0_sum.py diff --git a/data_structures/arrays/find_triplets_with_0_sum.py b/data_structures/arrays/find_triplets_with_0_sum.py new file mode 100644 index 000000000..8217ff857 --- /dev/null +++ b/data_structures/arrays/find_triplets_with_0_sum.py @@ -0,0 +1,24 @@ +from itertools import combinations + + +def find_triplets_with_0_sum(nums: list[int]) -> list[list[int]]: + """ + Given a list of integers, return elements a, b, c such that a + b + c = 0. + Args: + nums: list of integers + Returns: + list of lists of integers where sum(each_list) == 0 + Examples: + >>> find_triplets_with_0_sum([-1, 0, 1, 2, -1, -4]) + [[-1, -1, 2], [-1, 0, 1]] + >>> find_triplets_with_0_sum([]) + [] + >>> find_triplets_with_0_sum([0, 0, 0]) + [[0, 0, 0]] + >>> find_triplets_with_0_sum([1, 2, 3, 0, -1, -2, -3]) + [[-3, 0, 3], [-3, 1, 2], [-2, -1, 3], [-2, 0, 2], [-1, 0, 1]] + """ + return [ + list(x) + for x in sorted({abc for abc in combinations(sorted(nums), 3) if not sum(abc)}) + ]