Menu
CoddyTech

3Sum

You get a list of integers nums. Find every triplet [a, b, c] of values taken from three different positions of nums with a + b + c = 0. Write each triplet in non-decreasing order (a ≤ b ≤ c) and list each distinct triplet once, even when several choices of positions produce it. Return the triplets sorted by their first value, then by their second.

Function

threeSum(nums: integer-array) → integer-2d-array
numsinteger-array
the list of integers, with at least three elements
Returnsinteger-2d-array
every distinct triplet that adds up to 0, each in non-decreasing order, the list sorted

Constraints

  • 3 ≤ nums.length ≤ 3000
  • -105 ≤ nums[i] ≤ 105
  • At least one triplet adds up to 0.
  • Two triplets are the same when they hold the same three values.

Examples

Input
nums = [-2, 0, 1, 1, -1, 2]
Output
[[-2, 0, 2], [-2, 1, 1], [-1, 0, 1]]
Explanation
-2 + 0 + 2, -2 + 1 + 1 and -1 + 0 + 1 all make 0. [-2, 1, 1] may use the value 1 twice because 1 sits at two positions, while [-1, 0, 1] can be built with either 1 but appears once.

lock icon+15 hidden tests on Submit

challenge icon

Follow-up

The same pattern solves 4Sum: fix two values and run two pointers on the rest. Can you write it in O(n³) and keep the duplicate rules right at every level?

Reset code
def threeSum(nums):
    # Write code here
Test cases

Case 1

Case 2

Input

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

Expected

[[-2, 0, 2], [-2, 1, 1], [-1, 0, 1]]