Skip to content

add Three sum #9177

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Oct 1, 2023
Merged
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions maths/three_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""
The "Three Sum" problem is a commonly encountered problem in computer
science and data analysis.the Three Sum problem has practical applications
in various fields, including data analysis, optimization, algorithmic research,
pattern recognition, and cryptography. Its versatility makes it a valuable problem
for both theoretical analysis and real-world problem-solving.

"""


def three_sum(nums: list[int]) -> list[list[int]]:
"""
Find all unique triplets in a sorted array of integers that sum up to zero.

Args:
nums: A sorted list of integers.

Returns:
A list of lists containing unique triplets that sum up to zero.

Example:
>>> three_sum([-1, 0, 1, 2, -1, -4])
[[-1, -1, 2], [-1, 0, 1]]
>>> three_sum([1, 2, 3, 4])
[]

"""
nums.sort()
ans = []
for i in range(len(nums) - 2):
if i == 0 or (nums[i] != nums[i - 1]):
low, high, c = i + 1, len(nums) - 1, 0 - nums[i]
while low < high:
if nums[low] + nums[high] == c:
ans.append([nums[i], nums[low], nums[high]])

while low < high and nums[low] == nums[low + 1]:
low += 1
while low < high and nums[high] == nums[high - 1]:
high -= 1

low += 1
high -= 1
elif nums[low] + nums[high] < c:
low += 1
else:
high -= 1
return ans


# Run the doctests
if __name__ == "__main__":
import doctest

doctest.testmod()