The provided code defines a solution for the 3Sum problem, which finds all unique triplets in an array that sum to zero. It sorts the input list, builds a mapping of values to their indices, and handles an edge case for triplets of zeros. The main logic is implemented in a helper function that uses a set to track seen numbers and checks for valid pairs that complete the triplet.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
7 views
6sum Coding Solution
The provided code defines a solution for the 3Sum problem, which finds all unique triplets in an array that sum to zero. It sorts the input list, builds a mapping of values to their indices, and handles an edge case for triplets of zeros. The main logic is implemented in a helper function that uses a set to track seen numbers and checks for valid pairs that complete the triplet.
for i, num in enumerate(nums): index_map.setdefault(num, []).append(i)
# Edge case: [0, 0, 0]
if index_map.get(0, []) and len(index_map[0]) >= 3: res.append([0, 0, 0])
def twoSum(start_idx, target):
seen = set() for i in range(start_idx, n): a = nums[i] b = -target - a if a in seen: continue if b in index_map and index_map[b][-1] > index_map[a][0]: res.append([target, a, b]) seen.add(a)
for i in range(n): a = nums[i] if a == 0 or (i > 0 and a == nums[i - 1]): continue twoSum(i + 1, a)