Find all unique triplets in an array that sum to a target value.
Code
Algorithmsa = arr.sort
result = []
(0...a.length - 2).each do |i|
next if i > 0 && a[i] == a[i - 1]
l, r = i + 1, a.length - 1
while l < r
s = a[i] + a[l] + a[r]
if s == target
result << [a[i], a[l], a[r]]
l += 1 while l < r && a[l] == a[l + 1]
r -= 1 while l < r && a[r] == a[r - 1]
l += 1; r -= 1
elsif s < target then l += 1
else r -= 1
end
end
end
return resultParameters
Array of numbers
Target sum
Server
More Ruby Snippets
Array Difference
Find elements in the first array that are not present in the second array.
Array Frequencies
Count how many times each value appears in an array and return a frequency map.
Array Head
Get the first n elements of an array.
Array Intersection
Find common elements that exist in both arrays.
Array Tail
Get the last n elements of an array.
Array Union
Combine two arrays and remove duplicates to produce a union.