Sign inEnroll free
DSA Visualizer · 25 visualizations3Sum
MediumTwo Pointers

3Sum

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, j != k, and nums[i] + nums[j] + nums[k] == 0. The solution set must not contain duplicate triplets.

The step-through player is coming for this one. Two Sum has the full animation today; the rest are being authored in the admin.
Pythontime O(n²) · space O(1)
def threeSum(nums: list[int]) -> list[list[int]]:
    nums.sort()
    res = []
    for i, a in enumerate(nums):
        if i > 0 and a == nums[i-1]: continue
        l, r = i + 1, len(nums) - 1
        while l < r:
            s = a + nums[l] + nums[r]
            if s == 0:
                res.append([a, nums[l], nums[r]])
                l += 1
                while l < r and nums[l] == nums[l-1]: l += 1
            elif s < 0: l += 1
            else: r -= 1
    return res
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free
Watch the video walkthrough