You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. The function should find all triplets in the array that sum up to the target sum and return a two-dimensional array of all these triplets. The numbers in each triplet should be ordered in ascending order, and the triplets themselves should be ordered in ascending order with respect to the numbers they hold.
2
+
3
+
# If no three numbers sum up to the target sum, the function should return an empty array.
4
+
5
+
# Sample Input
6
+
# array = [12, 3, 1, 2, -6, 5, -8, 6]
7
+
# targetSum = 0
8
+
# Sample Output
9
+
# [[-8, 2, 6], [-8, 3, 5], [-6, 1, 5]]
10
+
require'set'
11
+
12
+
defthree_number_sum(nums,target)
13
+
returnifnums.length < 3
14
+
15
+
output=[]
16
+
nums.sort!
17
+
Range.new(0,nums.length - 2).eachdo |i|
18
+
left=i + 1
19
+
right=nums.length - 1
20
+
whileleft < right
21
+
sum=nums[i] + nums[left] + nums[right]
22
+
ifsum == target
23
+
output << [nums[i],nums[left],nums[right]]
24
+
left += 1
25
+
right -= 1
26
+
elsifsum < target
27
+
left += 1
28
+
else
29
+
right -= 1
30
+
end
31
+
end
32
+
end
33
+
output.to_a
34
+
end
35
+
36
+
# Leet code solution.
37
+
# Here the variation is, nums can have dublicate values and output should have uniq valeus only
# Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. The function should find all quadruplets in the array that sum up to the target sum and return a two-dimensional array of all these quadruplets in no particular order.
3
+
# If no four numbers sum up to the target sum, the function should return an empty array.
0 commit comments