From 13a2fe09b5d4e4fcdce6abc651792d56205ee465 Mon Sep 17 00:00:00 2001 From: Jessica Kwok Date: Tue, 9 Mar 2021 14:49:17 -0800 Subject: [PATCH] Hash table approach --- .../arrays/find_all_duplicates_in_an_array.rb | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/data_structures/arrays/find_all_duplicates_in_an_array.rb b/data_structures/arrays/find_all_duplicates_in_an_array.rb index b8b23b9..b507b98 100644 --- a/data_structures/arrays/find_all_duplicates_in_an_array.rb +++ b/data_structures/arrays/find_all_duplicates_in_an_array.rb @@ -55,4 +55,34 @@ Benchmark.bmbm do |x| x.report('execute algorithm') do print find_duplicates_2(long_array) end +end + +def find_duplicates_3(array) + result_hash = {} + result_array = [] + # loop through array and build a hash with counters + # where the key is the array element and the counter is the value + # increase counter when duplicate is found + array.each do |num| + if result_hash[num].nil? + result_hash[num] = 1 + else + result_hash[num] += 1 + end + end + # loop through hash and look for values > 1 + result_hash.each do |k, v| + if v > 1 + result_array.push(k) + end + end + # return keys + result_array +end + +require 'benchmark' +Benchmark.bmbm do |x| + x.report('execute algorithm') do + print find_duplicates_3(array) + end end \ No newline at end of file