How to minimize number of lookups in a Hash?

2 weeks ago 21
ARTICLE AD BOX

say you want to find the first duplicate an an array. you could do something like this:

cnt = {}; [ 11, 22, 77, 22, 33 ].each_with_index{|x,i| j=cnt[x]; ## <1> break [x,j,i] if j cnt[x] = i ## <2> } # => [ 22, 1, 3 ]

this is O(n) as long a Ruby Hash is O(1) for lookup and insert.
but still it does lookup two times ( <1>, <2>) . :-(
**Is there a way to avoid it? **
something like this:

cnt = {} some_array.each_with_index{ |x,i| j = cnt.exchange_value_at( x, i ); break [ x,j,i] if j }

Yes, I could easily implement such a method:
`def exchange( k, val ); old, self[k] = self[k], val; return old ; end`
but this would only hide the 2nd lookup. it would not avoid it.

Read Entire Article