Merge pull request #117 from TheAlgorithms/add-valid-anagram-hash-approach

Valid anagram: hash table approach
This commit is contained in:
Vitor Oliveira 2021-04-01 09:22:57 -07:00 committed by GitHub
commit b72876329f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 64 additions and 1 deletions

View file

@ -32,6 +32,7 @@
* [Postorder Traversal](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/binary_trees/postorder_traversal.rb)
* [Preorder Traversal](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/binary_trees/preorder_traversal.rb)
* Hash Table
* [Anagram Checker](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/anagram_checker.rb)
* [Find All Duplicates In An Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/find_all_duplicates_in_an_array.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)

View file

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

View file

@ -0,0 +1,62 @@
# 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