Given two strings, I would like to determine whether or not they are anagrams of one another. Here is the solution that I came up with:
# output messages
def anagram
puts "Anagram!"
exit
end
def not_anagram
puts "Not an anagram!"
exit
end
# main method
if __FILE__ == $0
# read two strings from the command line
first, second = gets.chomp, gets.chomp
# special case 1
not_anagram if first.length != second.length
# special case 2
anagram if first == second
# general case
# Two strings must have the exact same number of characters in the
# correct case to be anagrams.
# We can sort both strings and compare the results
if first.chars.sort.join == second.chars.sort.join
anagram
else
not_anagram
end
end
But I am thinking that there is probably a better one. I analyzed the efficiency of this solution, and came up with:
chars
: splits a string into an array of characters O(n)
sort
: sorts a string alphabetically, I don't know how sort is implemented in Ruby but I assumed O(n log n)
since that is the generally best known sorting efficiencyjoin
: builds a string from an array of characters O(n)
==
: The string comparison itself will have to examine every character of the strings 2*O(n)
Given the above, I categorized the efficiency of the entire solution as O(n log n)
since sorting had the highest efficiency. Is there a better way to do this that is more efficient than O(n log n)
?
Anagram Solver is a tool used to help players rearrange letters to generate all the possible words from them. You input the letters, and Anagram Maker gives you the edge to win Scrabble, Words With Friends, or any other word game.
Android anagram solvers It boasts a library of over 310,000 words with a clean, easy-to-use UI. Additionally, it supports multi-word anagrams, various filters, blank letters for board games, and word definitions as well. There really isn't much else to it. The app is simple, it works well, and it's easy to use.
To solve anagrams, rearrange the given letters to uncover hidden words or phrases. Try reorganizing the letters into a recognizable pattern or rearrange them into new groupings to give you a fresh perspective. For example, draw a shape, like a circle, and write the letters around it.
Your big O should be O(n*lg(n))
since the sort is the limiting function. If you try it with very big anagrams you will see a loss of performance higher than expected for an O(n)
solution.
You can do an O(n)
solution by comparing counts in two maps of characters => character counts.
There are definitely other solutions that work with approximately the same complexity but I don't think you can come up with anything faster than O(n)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With