#15

3Sum

MediumTwo PointersHas vizArrayTwo Pointers
Related studio

Problem

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Example 1

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

Output: [[-1,-1,2],[-1,0,1]]

The distinct triplets that sum to 0.

Example 2

Input: nums = [0,1,1]

Output: []

The only possible triplet does not sum to 0.

Example 3

Input: nums = [0,0,0]

Output: [[0,0,0]]

The only possible triplet sums to 0.

Constraints

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

Explanation

3Sum is a Medium interview problem tagged [Array, Two Pointers]. The winning approach is typically **Two Pointers**.

Intuition

Each pointer only moves forward/backward once, guaranteeing O(n) after any required sort.

Approach

Place two indices and move them based on a comparison or invariant (sorted order, palindrome symmetry, partition).

  1. Establish the invariant (e.g., array sorted).
  2. Initialize L and R.
  3. Move the pointer that improves the condition.
  4. Handle duplicates carefully if uniqueness is required.

Solution

Curated solution in C#, Python, Java, JavaScript, and C++ — switch languages with the tabs.

Exact solutionTwo Pointers

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n log n) or O(n)

Space: O(n)

Before coding, restate the problem, name the pattern (Two Pointers), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #15 3Sum as understood when the pattern clicks.