diff --git a/data_structures/arrays/strings/anagram_checker.rb b/data_structures/arrays/strings/anagram_checker.rb index bcd5e36..1918b07 100644 --- a/data_structures/arrays/strings/anagram_checker.rb +++ b/data_structures/arrays/strings/anagram_checker.rb @@ -15,7 +15,7 @@ # @return {Boolean} # -# Approach 1: Sort and Compare +# Approach: Sort and Compare # # Complexity analysis: # diff --git a/data_structures/hash_table/anagram_checker.rb b/data_structures/hash_table/anagram_checker.rb new file mode 100644 index 0000000..43163d4 --- /dev/null +++ b/data_structures/hash_table/anagram_checker.rb @@ -0,0 +1,55 @@ +# Challenge name: Is anagram +# +# Given two strings s and t , write a function to determine +# if t is an anagram of s. +# +# Note: +# You may assume the string contains only lowercase alphabets. +# +# Follow up: +# What if the inputs contain unicode characters? +# How would you adapt your solution to such case? +# +# @param {String} s +# @param {String} t +# @return {Boolean} + +# +# Approach: Hash table +# +# Complexity analysis: +# +# Time complexity: O(n). Time complexity is O(n) since accessing the counter table is a constant time operation. +# Space complexity: O(1). Although we do use extra space, the space complexity is O(1) because the table's size stays constant no matter how large n is. +# +def is_anagram(s, t) + s_length = s.length + t_length = t.length + counter = Hash.new(0) + + return false unless s_length == t_length + + (0...s_length).each do |i| + counter[s[i]] += 1 + counter[t[i]] -= 1 + end + + counter.each do |k, v| + return false unless v == 0 + end + + true +end + +s = 'anagram' +t = 'nagaram' +puts(is_anagram(s, t)) +# => true +s = 'rat' +t = 'car' +puts(is_anagram(s, t)) +# => false +s = 'a' +t = 'ab' +puts(is_anagram(s, t)) +# => false