MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / triplet_sum

Function triplet_sum

python3/Two Pointers/triplet_sum.py:4–21  ·  view source on GitHub ↗
(nums: List[int])

Source from the content-addressed store, hash-verified

2
3
4def triplet_sum(nums: List[int]) -> List[List[int]]:
5 triplets = []
6 nums.sort()
7 for i in range(len(nums)):
8 # Optimization: triplets consisting of only positive numbers
9 # will never sum to 0.
10
11 if nums[i] > 0:
12 break
13 # To avoid duplicate triplets, skip 'a' if it's the same as
14 # the previous number.
15 if i > 0 and nums[i] == nums[i - 1]:
16 continue
17 # Find all pairs that sum to a target of '-a' (-nums[i]).
18 pairs = pair_sum_sorted_all_pairs(nums, i + 1, -nums[i])
19 for pair in pairs:
20 triplets.append([nums[i]] + pair)
21 return triplets
22
23def pair_sum_sorted_all_pairs(nums: List[int], start: int, target: int) -> List[List[int]]:
24 pairs = []

Callers

nothing calls this directly

Calls 1

Tested by

no test coverage detected