@@ -81,7 +81,82 @@ def find_triplets_with_0_sum_hashing(arr: list[int]) -> list[list[int]]:
81
81
return output_arr
82
82
83
83
84
+ # Two pointer approach to find triplets with zero sum
85
+
86
+ """
87
+ Why is it the best?
88
+ 1. Faster than brute force due to sorting and then two pointers scanning.
89
+
90
+ 2. No extra space needed (except for sorting).
91
+
92
+ 3. Handles Duplicate efficiently by skipping repeated values.
93
+ """
94
+ def find_triplets_with_0_sum_two_pointer (arr : list [int ]) -> list [list [int ]]:
95
+ """
96
+ Function for finding the triplets with a given sum in the array using hashing.
97
+
98
+ Given a list of integers, return elements a, b, c such that a + b + c = 0.
99
+
100
+ Args:
101
+ nums: list of integers
102
+ Returns:
103
+ list of lists of integers where sum(each_list) == 0
104
+ Examples:
105
+ >>> find_triplets_with_0_sum_two_pointer([-1, 0, 1, 2, -1, -4])
106
+ [[-1, 0, 1], [-1, -1, 2]]
107
+ >>> find_triplets_with_0_sum_two_pointer([])
108
+ []
109
+ >>> find_triplets_with_0_sum_two_pointer([0, 0, 0])
110
+ [[0, 0, 0]]
111
+ >>> find_triplets_with_0_sum_two_pointer([1, 2, 3, 0, -1, -2, -3])
112
+ [[-1, 0, 1], [-3, 1, 2], [-2, 0, 2], [-2, -1, 3], [-3, 0, 3]]
113
+
114
+ Time complexity: O(N^2)
115
+ Auxiliary Space: O(1) (excluding output storage)
116
+
117
+ """
118
+
119
+ # Step 1: Sort the array to facilitate the two pointer approach
120
+ nums .sort ()
121
+ triplets = [] # list to store the valid triplets
122
+ n = len (nums )
123
+
124
+ # Step 2: iterate through the array, fixing one number at a time
125
+ for i in range (n - 2 ): # We need atleast 3 elements for a triplet
126
+ # skip duplicate elements for the first number
127
+ if i > 0 and nums [i ] == nums [i - 1 ]:
128
+ continue #Move to the distinct number
129
+
130
+ # Step 3: Use the two pointer technique to find pairs that sum up to -nums[i]
131
+ left , right = i + 1 , n - 1 # Initialize two pointers
132
+ while left < right :
133
+ total = nums [i ] + nums [left ] + nums [right ] #Calculate sum of three numbers
134
+
135
+ if total == 0 :
136
+ # If the sum is zero, we found a valid triplet
137
+ triplets .append ([nums [i ], nums [left ], nums [right ]])
138
+
139
+ # Move both pointers to look for the next unique pair
140
+ left += 1
141
+ right -= 1
142
+
143
+ # skip duplicate values for the second and third numbers
144
+ while left < right and nums [left ] == nums [left - 1 ]:
145
+ left += 1
146
+ while left < right and nums [right ] == nums [right + 1 ]:
147
+ right -= 1
148
+
149
+ elif total < 0 :
150
+ # If sum is less than zero, move the left pointer to the right
151
+ left += 1
152
+ else :
153
+ # If sum is greater than zero, move the right pointer to the left
154
+ right -= 1
155
+ return triplets
156
+
157
+
84
158
if __name__ == "__main__" :
85
159
from doctest import testmod
86
160
87
161
testmod ()
162
+
0 commit comments