Triplets

tags: complimentary-number

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.

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

Constraints

  • 0 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5

First Version

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# @param {Integer[]} nums
# @return {Integer[][]}
def three_sum(nums)
  output = []

  set = Set.new(nums)
    
  for i in (0..nums.size-3)
    target = -nums[i+1] - nums[i+2] 
    if set.include?(target)
      output << [nums[i+1], nums[i+2], target]
    end
  end
  
  output
end

Input
[0,0,0,0]
Output
[[0,0,0],[0,0,0]]
Expected
[[0,0,0]]

Second Version

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def three_sum(nums)
  output = []

  set = Set.new(nums)
    
  for i in (0..nums.size-3)
    target = -nums[i+1] - nums[i+2] 
    if set.include?(target)
      candidate = [nums[i+1], nums[i+2], target]
      unless output.include?(candidate)
        output << candidate
      end
    end
  end
  
  output
end

Input
[3,-2,1,0]
Output
[[-2,1,1]]
Expected
[]

Working Version

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
require 'set'

# @param {Integer[]} nums
# @return {Integer[][]}
def three_sum(nums)
  output = []
  nums.sort!

  set = Set.new(nums)
    
  for i in (0..nums.size-2)
    target = nums[i] + nums[i+1] 
    if set.include?(-target)
      output << [nums[i], nums[i+1], -target]
    end
  end
  
  output
end

nums = [-1,0,1,2,-1,-4]
p three_sum(nums)