Hash Tables
First Non-Repeating Value
Find the first input value whose final frequency is one.
Algorithm
Canonical input [3, 5, 2, 5, 3, 8, 2] prints 8.
The replay uses the same input in every language, so this Ruby DSA
implementation can be compared directly with the rest of the DSA track.
Basic Implementation
basic.rb
arr = [3, 5, 2, 5, 3, 8, 2]
count = Hash.new(0)
arr.each { |value| count[value] += 1 }
arr.each do |value|
if count[value] == 1
puts value
break
end
end
Complexity
- Time: O(n) average
- Space: O(k) for k distinct values
Implementation notes
arris a Ruby array of integers, not a string, so both passes iterate values witharr.each.count = Hash.new(0)creates a RubyHashwhose missing keys read as0.- The counting pass uses
count[value] += 1; the default value makes the first increment write1without a separate key check. - After the first pass, the trace shows the frequency table as
{3: 2, 5: 2, 2: 2, 8: 1}. - The second pass scans the original array order again, checking
count[value] == 1. - Values
3,5,2,5, and3are skipped because their counts are2. - When the scan reaches value
8at index5, the source prints it withputs valueand exits the loop withbreak. - The checked output is the single line
8; the source never prints the hash table itself.
two-pass lookup
The first pass builds a frequency table. The second pass keeps the original order and stops at the first value with frequency one.