DSA Patterns (Multi-Lang)•Part 3: Two Pointers & Sliding Window (19 - 28)
3Sum.
In Simple Words:
Sort the array. Fix element $i$ (skipping duplicates). Run Two Sum II with two pointers on the remainder to find nums[l] + nums[r] === -nums[i].
- Time: $O(N^2)$ | Space: $O(1)$ auxiliary
Multi-Language SolutionsPython 3 • JavaScript • TypeScript • Java • C++
Switch tabs or choose Alldef threeSum(nums: list[int]) -> list[list[int]]:
nums.sort()
res = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
l, r = i + 1, len(nums) - 1
while l < r:
total = nums[i] + nums[l] + nums[r]
if total == 0:
res.append([nums[i], nums[l], nums[r]])
while l < r and nums[l] == nums[l + 1]: l += 1
while l < r and nums[r] == nums[r - 1]: r -= 1
l += 1; r -= 1
elif total < 0:
l += 1
else:
r -= 1
return res