Arrays and Iteration
Two-Sum with Hash Lookup
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}]"
arr ← [2, 7, 11, 4, 5], target ← 9, seen ← {}
1arr = [2, 7, 11, 4, 5]2target = 9values this step[2, 7, 11, 4, 5]arr9target{}seenseen ← {2: 0}, hit ← no
8value = arr[i]9need = target - value10if seen.key?(need)values this step{} → {2: 0}seennohit0i2arr[i]7needhit ← 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 RubyHashfrom array value to its currently recorded index.- The scan uses a manual
while i < arr.lengthloop, readingvalue = arr[i]before computingneed = target - value. - Lookup uses
seen.key?(need), which distinguishes a stored index like0from a missing key. - On a hit, the source assigns
first = seen[need]andsecond = i, then exits immediately withbreak. - On a miss,
seen[value] = irecords the current value after the complement check, so the same array slot is not paired with itself. - The trace records
i = 0as a miss for need7, then stores{2: 0}. - At
i = 1, value7needs2, hits the hash, and produces result[0, 1]. - The final
puts "[#{first}, #{second}]"formats the two indices as a small bracketed string.