LeetMotion
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i ≠ j ≠ k and nums[i] + nums[j] + nums[k] == 0.
The solution set must not contain duplicate triplets.
Try every combination of three indices and check if their values sum to zero. Use a set to deduplicate results.
i, j, k with i < j < k.nums[i] + nums[j] + nums[k] == 0, add the sorted triplet to a result set.Why it's not optimal: O(n³) — too slow for n up to 3000. Sorting + two-pointer reduces this to O(n²).
def threeSum(nums): res = set() for i in range(len(nums)): for j in range(i + 1, len(nums)): for k in range(j + 1, len(nums)): if nums[i] + nums[j] + nums[k] == 0: res.add(tuple(sorted([nums[i], nums[j], nums[k]]))) return [list(t) for t in res]
Sort the array first. Fix one element at index i, then use two pointers L and R on the remaining subarray to find pairs that sum to -nums[i]. Skip duplicate values of i, L, and R to avoid duplicate triplets.
nums[i] > 0, no triplet can sum to 0 — break early.i (same as previous).L=i+1, R=n-1. If sum is 0, record triplet and advance both. If sum < 0, increment L. If sum > 0, decrement R.
Discussion
…