Valid anagram: hash table approach

This commit is contained in:
Vitor Oliveira 2021-03-31 19:02:57 -07:00
parent a472f9a6ff
commit 4674c2d97b
2 changed files with 56 additions and 1 deletions

View file

@ -15,7 +15,7 @@
# @return {Boolean}
#
# Approach 1: Sort and Compare
# Approach: Sort and Compare
#
# Complexity analysis:
#

View file

@ -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