oneby7

Two Pointers Pointers from both ends

154. 3Sum

Medium 147 DSA Sheet

Given an integer array nums, return all triples [nums[i], nums[j], nums[k]] where i, j and k are different and nums[i] + nums[j] + nums[k] == 0.

The answer must not contain duplicate triples. Two triples are duplicates if they hold the same values, in any order. You can return the triples, and the values inside each one, in any order.

Example 1

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

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

Explanation: Three triples add up to 0: −3 + 1 + 2, −1 + (−1) + 2 and −1 + 0 + 1. The value 2 appears twice, so −3, 1 and 2 can be picked from two sets of positions, but the triple is listed once.

Example 2

Input: nums = [0, -5, 0, 5, 0]

Output: [[-5,0,5],[0,0,0]]

Explanation: −5 + 0 + 5 = 0, and the three zeros add up to 0 as well. Each triple appears once, although there are three zeros to pick from.

Example 3

Input: nums = [2147483647, -2147483648, 1, 0, 0]

Output: [[-2147483648,1,2147483647]]

Explanation: The values can be as large as a 32-bit integer allows. Here −2147483648 + 1 + 2147483647 = 0. No other three elements add up to 0, and two zeros are not enough for the triple 0, 0, 0.

Check your understanding

Work out the answer for this input before you write any code.

nums = [-1, 0, 1, 0, -1, 1]

Constraints

  • 1 ≤ nums.length ≤ 3000
  • -231 ≤ nums[i] ≤ 231 − 1

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.