From 60d4a4bcbce7b73a1bf48437ea92a973bb3caa7b Mon Sep 17 00:00:00 2001 From: Jessica Kwok Date: Tue, 1 Jun 2021 13:11:08 -0700 Subject: [PATCH] Add hash solution --- .../arrays/strings/common_characters.rb | 38 +++++++++++++++++-- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/data_structures/arrays/strings/common_characters.rb b/data_structures/arrays/strings/common_characters.rb index 42205aa..6d126c5 100644 --- a/data_structures/arrays/strings/common_characters.rb +++ b/data_structures/arrays/strings/common_characters.rb @@ -9,11 +9,43 @@ # You may return the answer in any order. # # Example 1: -# # Input: ["bella","label","roller"] # Output: ["e","l","l"] # # Example 2: -# # Input: ["cool","lock","cook"] -# Output: ["c","o"] \ No newline at end of file +# Output: ["c","o"] + +# +# Approach 1: Hash +# +# Time Complexity: O(n) +# +def common_characters(arr) + target_count = arr.count + + hash = Hash.new(0) + (0...target_count).each do |i| + arr[i].split('').each do |letter| + hash[letter] += 1 + end + end + + result = [] + hash.each do |k, v| + while v >= target_count + if v >= target_count + result << k + v -= target_count + end + end + end + + result +end + +puts common_characters(["bella","label","roller"]) +# => ["e","l","l"] + +puts common_characters(["cool","lock","cook"]) +# => ["c","o"] \ No newline at end of file