PIXELBANKv8.2.1
Menu

Three Sum

Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, j != k, and nums[i] + nums[j] + nums[k] == 0.

The solution set must not contain duplicate triplets. Output each triplet sorted, one per line, with triplets sorted lexicographically.

Example:

Input:
-1,0,1,2,-1,-4
Output:
-1 -1 2
-1 0 1
Reasoning:
  • The input array nums is first sorted to apply the two-pointer technique: [4,1,1,0,1,2][-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 nums[i]-nums[i].
  • For nums[0]=4nums[0] = -4, no triplet sums to 00, but for nums[1]=1nums[1] = -1, we find 1+0+1=0-1 + 0 + 1 = 0 and for nums[2]=1nums[2] = -1, we find 1+1+2=0-1 + -1 + 2 = 0.
  • These two unique triplets [1,0,1][-1, 0, 1] and [1,1,2][-1, -1, 2] are then sorted and output, resulting in the given sample output.

Constraints:

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

Test Results

0/0
Run code to see test results.