Skip to content

Commit d074c77

Browse files
Add two-pointer method for finding triplets with 0 sum
Implemented a new function to find unique triplets in an array that sum to zero using the two-pointer technique.
1 parent 3c88735 commit d074c77

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

data_structures/arrays/find_triplets_with_0_sum.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,57 @@ def find_triplets_with_0_sum_hashing(arr: list[int]) -> list[list[int]]:
7979

8080
# Return all the triplet combinations.
8181
return output_arr
82+
83+
def find_triplets_with_0_sum_two_pointers(nums: list[int]) -> list[list[int]]:
84+
"""
85+
Finds all unique triplets in the array which gives the sum of zero
86+
using the two-pointer technique.
87+
88+
Args:
89+
nums: list of integers
90+
Returns:
91+
list of lists of integers where sum(each_list) == 0
92+
93+
Examples:
94+
>>> find_triplets_with_0_sum_two_pointers([-1, 0, 1, 2, -1, -4])
95+
[[-1, -1, 2], [-1, 0, 1]]
96+
>>> find_triplets_with_0_sum_two_pointers([])
97+
[]
98+
>>> find_triplets_with_0_sum_two_pointers([0, 0, 0, 0])
99+
[[0, 0, 0]]
100+
101+
Time Complexity: O(N^2)
102+
Auxiliary Space: O(1) (excluding output)
103+
"""
104+
nums.sort()
105+
result = []
106+
n = len(nums)
107+
108+
for i in range(n - 2):
109+
if i > 0 and nums[i] == nums[i - 1]:
110+
continue
111+
112+
left, right = i + 1, n - 1
113+
114+
while left < right:
115+
total = nums[i] + nums[left] + nums[right]
116+
117+
if total == 0:
118+
result.append([nums[i], nums[left], nums[right]])
119+
left += 1
120+
right -= 1
121+
122+
while left < right and nums[left] == nums[left - 1]:
123+
left += 1
124+
while left < right and nums[right] == nums[right + 1]:
125+
right -= 1
126+
127+
elif total < 0:
128+
left += 1
129+
else:
130+
right -= 1
131+
132+
return result
82133

83134

84135
if __name__ == "__main__":

0 commit comments

Comments
 (0)