Skip to solution
mediumDSA

How do you solve the 3Sum problem?

333 views
01

Understand the problem

Explain finding triplets summing to zero.

arraystwo-pointers
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Sort the array, then fix one element and use two pointers on the rest to find pairs summing to its negation. Skip duplicates at each level to avoid repeated triplets. Sorting is O(n log n) and the scan is O(n²) overall.

Solution ready — 2 min read

Classified // press E to declassify

04

Read the code

Sort + two pointers
Run Playground
def three_sum(nums):
    nums.sort()
    res = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue                      # skip duplicate fixed value
        left, right = i + 1, len(nums) - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total < 0:
                left += 1
            elif total > 0:
                right -= 1
            else:
                res.append([nums[i], nums[left], nums[right]])
                left += 1; right -= 1
                while left < right and nums[left] == nums[left - 1]:
                    left += 1
                while left < right and nums[right] == nums[right + 1]:
                    right -= 1
    return res


# --- demo ---
print(three_sum([-1, 0, 1, 2, -1, -4]))   # [[-1, -1, 2], [-1, 0, 1]]
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 81 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.

Back to track