rubyarrays

How to find and return a duplicate value in array


arr is array of strings:

["hello", "world", "stack", "overflow", "hello", "again"]

What would be an easy and elegant way to check if arr has duplicates, and if so, return one of them (no matter which)?

Examples:

["A", "B", "C", "B", "A"]    # => "A" or "B"
["A", "B", "C"]              # => nil

Solution

  • a = ["A", "B", "C", "B", "A"]
    a.detect{ |e| a.count(e) > 1 }
    

    I know this isn't very elegant answer, but I love it. It's beautiful one liner code. And works perfectly fine unless you need to process huge data set.

    Looking for faster solution? Here you go!

    def find_one_using_hash_map(array)
      map = {}
      dup = nil
      array.each do |v|
        map[v] = (map[v] || 0 ) + 1
    
        if map[v] > 1
          dup = v
          break
        end
      end
    
      return dup
    end
    

    It's linear, O(n), but now needs to manage multiple lines-of-code, needs test cases, etc.

    If you need an even faster solution, maybe try C instead.

    And here is the gist comparing different solutions: https://gist.github.com/naveed-ahmad/8f0b926ffccf5fbd206a1cc58ce9743e