Skip to content

Instantly share code, notes, and snippets.

@strychemi
Created January 25, 2016 00:44
Show Gist options
  • Select an option

  • Save strychemi/76487fc548be7d42714b to your computer and use it in GitHub Desktop.

Select an option

Save strychemi/76487fc548be7d42714b to your computer and use it in GitHub Desktop.
=begin
Given an array of positive integers, find all pairs that have a difference of a specified value k.
Pass: O(n^2)
Super Extra Credit: O(n)
=end
# O(n^2) Solution
def difference_pairs(array, k)
# uniq is O(n), or you can implement one using a Hash
array.uniq!
results = []
# test every combination of integers using a nested iterators O(n^2)
array.each_with_index do |first, first_index|
array[first_index+1..-1].each_with_index do |second, second_index|
difference = (first - second).abs
results << [first, second] if difference == k
end
end
return results
end
p difference_pairs([1, 9, 4, 2, 2, 4, 3, 8], 5)
# O(n) Solution
def difference_pairs(array, k)
# implementing uniq in-house O(n)
unique = {}
array.each do |num|
unique[num] = num
end
results = []
# instead of checking a - b = diff, we check if diff + b = a
# i.e., we check if a exists in the hash
unique.each do |key, value|
results << [value, unique[k + value]] if unique[k + value]
end
return results
end
p difference_pairs([1, 9, 4, 2, 2, 4, 3, 8], 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment