Walk the array once, storing seen values in a lookup table. When the complement is already present, the result indices are known.

Algorithm

Basic Implementation

basic.rb
arr = [2, 7, 11, 4, 5]
target = 9
seen = {}
first = -1
second = -1
i = 0
while i < arr.length
	value = arr[i]
	need = target - value
	if seen.key?(need)
		first = seen[need]
		second = i
		break
	end
	seen[value] = i
	i += 1
end
puts "[#{first}, #{second}]"

Complexity

  • Time: O(n) average
  • Space: O(n)

Implementation notes

  • seen = {} is a Ruby Hash from array value to its currently recorded index.
  • The scan uses a manual while i < arr.length loop, reading value = arr[i] before computing need = target - value.
  • Lookup uses seen.key?(need), which distinguishes a stored index like 0 from a missing key.
  • On a hit, the source assigns first = seen[need] and second = i, then exits immediately with break.
  • On a miss, seen[value] = i records the current value after the complement check, so the same array slot is not paired with itself.
  • The trace records i = 0 as a miss for need 7, then stores {2: 0}.
  • At i = 1, value 7 needs 2, hits the hash, and produces result [0, 1].
  • The final puts "[#{first}, #{second}]" formats the two indices as a small bracketed string.
execution replay The checked-in replay follows the language-neutral state table for `array-two-sum-hash`.
cross-language comparison This Ruby DSA version keeps the same data and final output as every other DSA book in this wave.