From d074c77c1e28c789e70d46cfdc72fccec3690b67 Mon Sep 17 00:00:00 2001 From: KavyadharshiniM06 Date: Tue, 20 Jan 2026 22:46:08 +0530 Subject: [PATCH 1/2] 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. --- .../arrays/find_triplets_with_0_sum.py | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/data_structures/arrays/find_triplets_with_0_sum.py b/data_structures/arrays/find_triplets_with_0_sum.py index 52e521906873..114fd037260e 100644 --- a/data_structures/arrays/find_triplets_with_0_sum.py +++ b/data_structures/arrays/find_triplets_with_0_sum.py @@ -79,6 +79,57 @@ def find_triplets_with_0_sum_hashing(arr: list[int]) -> list[list[int]]: # Return all the triplet combinations. return output_arr + +def find_triplets_with_0_sum_two_pointers(nums: list[int]) -> list[list[int]]: + """ + Finds all unique triplets in the array which gives the sum of zero + using the two-pointer technique. + + Args: + nums: list of integers + Returns: + list of lists of integers where sum(each_list) == 0 + + Examples: + >>> find_triplets_with_0_sum_two_pointers([-1, 0, 1, 2, -1, -4]) + [[-1, -1, 2], [-1, 0, 1]] + >>> find_triplets_with_0_sum_two_pointers([]) + [] + >>> find_triplets_with_0_sum_two_pointers([0, 0, 0, 0]) + [[0, 0, 0]] + + Time Complexity: O(N^2) + Auxiliary Space: O(1) (excluding output) + """ + nums.sort() + result = [] + n = len(nums) + + for i in range(n - 2): + if i > 0 and nums[i] == nums[i - 1]: + continue + + left, right = i + 1, n - 1 + + while left < right: + total = nums[i] + nums[left] + nums[right] + + if total == 0: + result.append([nums[i], nums[left], nums[right]]) + left += 1 + right -= 1 + + while left < right and nums[left] == nums[left - 1]: + left += 1 + while left < right and nums[right] == nums[right + 1]: + right -= 1 + + elif total < 0: + left += 1 + else: + right -= 1 + + return result if __name__ == "__main__": From c80deb53f0df1d71a3127d21a8d6336098ceea7c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 20 Jan 2026 17:30:21 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- data_structures/arrays/find_triplets_with_0_sum.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/data_structures/arrays/find_triplets_with_0_sum.py b/data_structures/arrays/find_triplets_with_0_sum.py index 114fd037260e..b436d51fcbf0 100644 --- a/data_structures/arrays/find_triplets_with_0_sum.py +++ b/data_structures/arrays/find_triplets_with_0_sum.py @@ -79,7 +79,8 @@ def find_triplets_with_0_sum_hashing(arr: list[int]) -> list[list[int]]: # Return all the triplet combinations. return output_arr - + + def find_triplets_with_0_sum_two_pointers(nums: list[int]) -> list[list[int]]: """ Finds all unique triplets in the array which gives the sum of zero