Skip to content

Instantly share code, notes, and snippets.

@seanhandley
Created June 10, 2024 06:53
Show Gist options
  • Save seanhandley/a47a0cb33c9ee6c142e2aaebb2702ffd to your computer and use it in GitHub Desktop.
Save seanhandley/a47a0cb33c9ee6c142e2aaebb2702ffd to your computer and use it in GitHub Desktop.
Write a function that takes an array of integers and a target sum, and returns all unique quadruplets [a, b, c, d] in the array such that a + b + c + d = target. If it's impossible, return an empty array.
def four_sum(collection, target)
collection.combination(4).
uniq.
select { |combination| combination.sum == target }.
map(&:sort).
sort
end
four_sum([1, 0, -1, 0, -2, 2], 0)
# => [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
four_sum([], 0)
# => []
four_sum([1, -2, -5, -4, -3, 3, 3, 5], -11)
# => [[-5, -4, -3, 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment