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
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 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.
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.