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

Algorithm

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.

Basic Implementation

basic.rb
Replay: real traced execution (multi-file project)
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}]"
  1. arr ← [2, 7, 11, 4, 5], target ← 9, seen ← {}

    1arr = [2, 7, 11, 4, 5]2target = 9
    values this step[2, 7, 11, 4, 5]arr9target{}seen
  2. seen ← {2: 0}, hit ← no

    8value = arr[i]9need = target - value10if seen.key?(need)
    values this step{} {2: 0}seennohit0i2arr[i]7need
  3. hit ← yes, result ← [0, 1]

    8value = arr[i]9need = target - value10if seen.key?(need)
    values this stepyeshit[0, 1]result1i7arr[i]2need{2: 0}seen

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.