diff --git a/DIRECTORY.md b/DIRECTORY.md index 55d05c5..f7adeec 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -55,6 +55,7 @@ * [Good Pairs](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/good_pairs.rb) * [Richest Customer Wealth](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/richest_customer_wealth.rb) * [Two Sum](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/two_sum.rb) + * [Uncommon Words](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/uncommon_words.rb) * Linked Lists * [Circular Linked List](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/linked_lists/circular_linked_list.rb) * [Doubly Linked List](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/linked_lists/doubly_linked_list.rb) diff --git a/data_structures/hash_table/uncommon_words.rb b/data_structures/hash_table/uncommon_words.rb new file mode 100644 index 0000000..ff0ace9 --- /dev/null +++ b/data_structures/hash_table/uncommon_words.rb @@ -0,0 +1,48 @@ +# Challenge name: Uncommon words from two sentences +# +# We are given two sentences A and B. +# (A sentence is a string of space separated words. +# Each word consists only of lowercase letters.) +# +# A word is uncommon if it appears exactly once in one of the sentences, +# and does not appear in the other sentence. +# +# Return a list of all uncommon words. +# You may return the list in any order. +# +# Example 1: +# Input: A = "this apple is sweet", B = "this apple is sour" +# Output: ["sweet","sour"] +# +# Example 2: +# Input: A = "apple apple", B = "banana" +# Output: ["banana"] + +# +# Approach 1: Hash +# +# Time Complexitiy: O(n) + +def find_uncommon_words(strA, strB) + array = strA.concat(" ", strB).split(" ") + hash = Hash.new(0) + result = [] + + array.each do |word| + hash[word] += 1 + end + + hash.each do |k, v| + if v < 2 + result.push(k) + end + end + + result +end + +puts find_uncommon_words("this apple is sweet", "this apple is sour") +# => ["sweet", "sour"] + +puts find_uncommon_words("apple apple", "banana") +# => ["banana"]