#15MediumTwo Pointers

3Sum

Sort + two-pointer inner scan to find all unique zero-sum triplets.

AmazonAdobeMicrosoftFacebookGoldman Sachs

Problem Statement

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.

Examples

Example 1

Input:nums = [-1,0,1,2,-1,-4]
Output:[[-1,-1,2],[-1,0,1]]

Example 2

Input:nums = [0,0,0]
Output:[[0,0,0]]

Constraints

  • 3 ≤ nums.length ≤ 3000
  • -10⁵ ≤ nums[i] ≤ 10⁵

Solutions

1
Brute Force — Three Nested Loops
TimeO(n³)SpaceO(n)

Try every possible triplet (i, j, k). Use a set to deduplicate. O(n³) — too slow for n=3000.

Visual Animation
def threeSum(nums: list[int]) -> list[list[int]]:
    result = set()
    n = len(nums)
    for i in range(n):
        for j in range(i+1, n):
            for k in range(j+1, n):
                if nums[i]+nums[j]+nums[k] == 0:
                    result.add(tuple(sorted([nums[i],nums[j],nums[k]])))
    return [list(t) for t in result]

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Two Pointers to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems