Two Sum

Find indices of two numbers in an array that add up to a target value using a hash map for O(n) time complexity.

Code

Algorithms
seen = {}
result = nil
arr.each_with_index do |num, i|
  complement = target - num
  if seen.key?(complement)
    result = [seen[complement], i]
    break
  end
  seen[num] = i
end
return result

Parameters

Array of numbers

Target sum

Server

More Ruby Snippets