@@ -22,3 +22,66 @@ def find_triplets_with_0_sum(nums: list[int]) -> list[list[int]]:
22
22
list (x )
23
23
for x in sorted ({abc for abc in combinations (sorted (nums ), 3 ) if not sum (abc )})
24
24
]
25
+
26
+
27
+ def find_triplets_with_0_sum_hashing (arr : list [int ]) -> list [list [int ]]:
28
+ """
29
+ Function for finding the triplets with a given sum in the array using hashing.
30
+
31
+ Given a list of integers, return elements a, b, c such that a + b + c = 0.
32
+
33
+ Args:
34
+ nums: list of integers
35
+ Returns:
36
+ list of lists of integers where sum(each_list) == 0
37
+ Examples:
38
+ >>> find_triplets_with_0_sum_hashing([-1, 0, 1, 2, -1, -4])
39
+ [[-1, 0, 1], [-1, -1, 2]]
40
+ >>> find_triplets_with_0_sum_hashing([])
41
+ []
42
+ >>> find_triplets_with_0_sum_hashing([0, 0, 0])
43
+ [[0, 0, 0]]
44
+ >>> find_triplets_with_0_sum_hashing([1, 2, 3, 0, -1, -2, -3])
45
+ [[-1, 0, 1], [-3, 1, 2], [-2, 0, 2], [-2, -1, 3], [-3, 0, 3]]
46
+
47
+ Time complexity: O(N^2)
48
+ Auxiliary Space: O(N)
49
+
50
+ """
51
+ target_sum = 0
52
+
53
+ # Initialize the final output array with blank.
54
+ output_arr = []
55
+
56
+ # Set the initial element as arr[i].
57
+ for index , item in enumerate (arr [:- 2 ]):
58
+ # to store second elements that can complement the final sum.
59
+ set_initialize = set ()
60
+
61
+ # current sum needed for reaching the target sum
62
+ current_sum = target_sum - item
63
+
64
+ # Traverse the subarray arr[i+1:].
65
+ for other_item in arr [index + 1 :]:
66
+ # required value for the second element
67
+ required_value = current_sum - other_item
68
+
69
+ # Verify if the desired value exists in the set.
70
+ if required_value in set_initialize :
71
+ # finding triplet elements combination.
72
+ combination_array = sorted ([item , other_item , required_value ])
73
+ if combination_array not in output_arr :
74
+ output_arr .append (combination_array )
75
+
76
+ # Include the current element in the set
77
+ # for subsequent complement verification.
78
+ set_initialize .add (other_item )
79
+
80
+ # Return all the triplet combinations.
81
+ return output_arr
82
+
83
+
84
+ if __name__ == "__main__" :
85
+ from doctest import testmod
86
+
87
+ testmod ()
0 commit comments