Skip to content

Commit 01f73f8

Browse files
KavyadharshiniM06pre-commit-ci[bot]cclauss
authored
Add two-pointer method for finding triplets with 0 sum (#14186)
* 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. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 51a19de commit 01f73f8

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

‎data_structures/arrays/find_triplets_with_0_sum.py‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,58 @@ def find_triplets_with_0_sum_hashing(arr: list[int]) -> list[list[int]]:
8181
return output_arr
8282

8383

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

0 commit comments

Comments
 (0)