AlgoInsight

DSA problem

3Sum

MediumTwo PointersPattern: Two Pointerstop75FreeAmazonGoogleFacebookMicrosoftApple

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.

Two triplets are considered duplicates if they contain the same three values, regardless of the order in which those values appear. The order of the triplets in the output and the order of values within each triplet do not matter.

Examples

Example 1
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: The distinct triplets summing to zero are [-1,-1,2] and [-1,0,1]. The triplet [0,0,0] is not present because there is only one 0.
Example 2
Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet [0,1,1] does not sum to zero, so the output is an empty list.
Example 3
Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums to zero, so it is the single answer.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

two-pointersarraysorting

Browse all DSA problems