DSA Tracker

Problem

Pattern this teaches:Two Pointers

Medium

3Sum

A medium Arrays interview guide. Task statement, worked examples, intuition, and step-by-step solutions.

Topic
Arrays
Sheets
3
Core for
26 roles

The problem

Given an integer array, find all unique triplets [nums[i], nums[j], nums[k]] with distinct indices that sum up to zero.

Example 1

Input
nums = [-3,1,2,-1,0,2]
Output
[[-3,1,2],[-1,0,1]]
Why
Two different value groups add up to 0: -3 + 1 + 2 and -1 + 0 + 1. The second 2 would only repeat the first group, so it adds nothing new.

Example 2

Input
nums = [1,2,4]
Output
[]
Why
All three numbers are positive, so no three of them can add up to 0.

Example 3

Input
nums = [0,0,0,0]
Output
[[0,0,0]]
Why
Any three of the four zeros add up to 0, but they all form the same group, so it is listed once.

Constraints

  • 3 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5

How to think about it

Updated 2026-09-29

Fixing one number turns the problem into finding two numbers in the remaining suffix that sum to -nums[i]. Sorting the array organizes duplicate values next to each other, allowing two pointers to sweep inward while skipping identical adjacent values to guarantee that every generated triplet is unique.

Approaches, worst first

  1. Triple nested loops with set deduplication

    time O(n^3) · space O(n)

    Iterate through all index triplets (i, j, k) with three nested loops, verify whether their sum is 0, sort the matched triplet, and insert it into a set to weed out duplicates. Extremely slow at cubic time and consumes significant memory for set overhead.

  2. Hash set complement lookup

    time O(n^2) · space O(n)

    Fix nums[i], then for the remaining elements maintain a hash set of visited values to find -nums[i] - nums[j]. Avoids the third loop, but still requires post-processing or set hashing to filter duplicate value combinations.

  3. Sort, then two-pointer scanWrite this one

    time O(n^2) · space O(1)

    Sort the array ascending. Iterate i from 0 to n - 3, skipping nums[i] == nums[i - 1]. Use two pointers low = i + 1 and high = n - 1 to find pairs summing to -nums[i]. On a match, record the triplet and advance past all identical neighbor values on both ends.

Where people lose marks · 3
  • Failing to skip duplicate values for the outer loop variable i, which generates duplicate triplet solutions.
  • Skipping duplicates only on one pointer instead of both left and right after recording a valid triplet.
  • Terminating the inner two-pointer search after the first match rather than continuing to search for other valid pairs with the same outer element.

Full solution

Sort, then fix one number and two-pointer scan the rest for the complement sum — O(n^2) time, O(1) extra space, and the sorted order makes duplicate-triplet skipping trivial on both pointers.

Python
from typing import List


def three_sum(nums: List[int]) -> List[List[int]]:
    nums.sort()
    n = len(nums)
    result = []
    for i in range(n - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue  # skip duplicate anchors
        if nums[i] > 0:
            break  # smallest remaining value is positive, no zero sum possible
        low, high = i + 1, n - 1
        while low < high:
            total = nums[i] + nums[low] + nums[high]
            if total < 0:
                low += 1
            elif total > 0:
                high -= 1
            else:
                result.append([nums[i], nums[low], nums[high]])
                low += 1
                high -= 1
                while low < high and nums[low] == nums[low - 1]:
                    low += 1
                while low < high and nums[high] == nums[high + 1]:
                    high -= 1
    return result
JavaScript
function threeSum(nums) {
  nums = [...nums].sort((a, b) => a - b);
  const n = nums.length;
  const result = [];
  for (let i = 0; i < n - 2; i++) {
    if (i > 0 && nums[i] === nums[i - 1]) continue; // skip duplicate anchors
    if (nums[i] > 0) break; // smallest remaining value is positive, no zero sum possible
    let low = i + 1;
    let high = n - 1;
    while (low < high) {
      const total = nums[i] + nums[low] + nums[high];
      if (total < 0) {
        low++;
      } else if (total > 0) {
        high--;
      } else {
        result.push([nums[i], nums[low], nums[high]]);
        low++;
        high--;
        while (low < high && nums[low] === nums[low - 1]) low++;
        while (low < high && nums[high] === nums[high + 1]) high--;
      }
    }
  }
  return result;
}
Try it in the editor

The theory behind it

Arrays — the ground this problem stands on. All Arrays problems

What Arrays is

An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.

When to reach for it

Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.

How the pattern works

Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.

More Arrays problems

Track in your role's order

Pick your target role and all 370 problems resequence to what that interview actually asks.

Start free

Problem set and role mapping as of .