PIXELBANKv9.1.0
Menu

Given an array of integers, find all unique triplets that sum to zero.

Output each triplet on a separate line, sorted, space-separated. Triplets sorted lexicographically.

Example:

Input:
-1,0,1,2,-1,-4
Output:
-1 -1 2
-1 0 1
Reasoning:
  • The input array is first sorted to apply the two-pointer technique: -4, -1, -1, 0, 1, 2
  • We iterate over the array and for each element, we use two pointers, one starting from the next element and one from the end, to find a pair that sums to the negation of the current element: −a=b+c-a = b + c
  • For -1, the pair (-1, 2) is found as −(−1)=−1+2-(-1) = -1 + 2, and for 0, the pair (0, 1) is not valid but (-1, 1) is, as −(−1)=−1+1-(-1) = -1 + 1 and 0=−1+10 = -1 + 1
  • The valid triplets are then output, sorted lexicographically: -1 -1 2 and -1 0 1

Constraints:

  • 3 <= len(nums) <= 3000
  • -10^5 <= nums[i] <= 10^5
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.