Search⌘ K
AI Features

3Sum

3Sum asks you to find every unique triplet in an integer array, including negative values, whose elements sum to zero using three distinct indices.

Statement

Given an integer array nums, find all unique triplets [nums[i], nums[j], nums[k]] where i, j, and k are distinct indices, such that the three elements sum to zero.

The result must not contain any duplicate triplets. The order of the output and the order of elements within each triplet does not matter.

Note: The solution set must only include unique triplets. Two triplets are considered duplicates if they contain the same elements regardless of ordering.

Constraints:

  • 3≤3 \leq nums.length ≤3000\leq 3000

  • −105≤-10^5 \leq nums[i] ≤105\leq 10^5

Examples

canvasAnimation-image
1 / 5

Understand the problem

Now, let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

3Sum

1.

Given nums = [-3, -3, 6, 1, 2, -3], how many unique triplets sum to zero?

A.

3

B.

2

C.

1

D.

0


1 / 5

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground.

Need a nudge?

Explore these hints—each one is designed to guide you a step closer to the solution.

Go
usercode > Solution.go
package main
func threeSum(nums []int) [][]int {
// Replace this placeholder return statement with your code
return [][]int{}
}
3Sum