MCPcopy
hub / github.com/keon/algorithms / three_sum

Function three_sum

algorithms/array/three_sum.py:17–53  ·  view source on GitHub ↗

Find all unique triplets in the array that sum to zero. Args: array: List of integers to search. Returns: Set of sorted tuples, each containing three integers summing to zero. Examples: >>> three_sum([-1, 0, 1, 2, -1, -4]) == {(-1, 0, 1), (-1, -1, 2)} T

(array: list[int])

Source from the content-addressed store, hash-verified

15
16
17def three_sum(array: list[int]) -> set[tuple[int, int, int]]:
18 """Find all unique triplets in the array that sum to zero.
19
20 Args:
21 array: List of integers to search.
22
23 Returns:
24 Set of sorted tuples, each containing three integers summing to zero.
25
26 Examples:
27 >>> three_sum([-1, 0, 1, 2, -1, -4]) == {(-1, 0, 1), (-1, -1, 2)}
28 True
29 """
30 result = set()
31 array.sort()
32 for i in range(len(array) - 2):
33 if i > 0 and array[i] == array[i - 1]:
34 continue
35 left, right = i + 1, len(array) - 1
36 while left < right:
37 current_sum = array[i] + array[left] + array[right]
38 if current_sum > 0:
39 right -= 1
40 elif current_sum < 0:
41 left += 1
42 else:
43 result.add((array[i], array[left], array[right]))
44
45 while left < right and array[left] == array[left + 1]:
46 left += 1
47
48 while left < right and array[right] == array[right - 1]:
49 right -= 1
50
51 left += 1
52 right -= 1
53 return result

Callers 1

test_three_sumMethod · 0.90

Calls 1

addMethod · 0.80

Tested by 1

test_three_sumMethod · 0.72