The problem doesn't state any special conditions (e.g., whether it is necessary to sort the groups of anagrams), so I assume a simple approach. For example, if the input is alert, acre, pool, race, care, loop, alter, later, then the output could be something like acre, race, care, alert, alter, later, pool, loop.
This problem could be solved using hashes. Example is below with the comments.
def anagrams(input) hash = Hash.new n = 0 # iterate over the array while n < input.length() # convert each string into characters and sort word = input[n].chars.sort # create a new key value if it doesn't exist hash[word] ||= [] # iterate over the remaining words in the array (n...input.length).each do |i| # compare each word in the remaining array with the first word # and add it to hash if it doesn't exist yet if word == input[i].chars.sort hash[word] << input[i] if !hash[word].include?(input[i]) end end n += 1 end # return only values of the hash converted into an array hash.values.flatten end input = ['alert', 'acre', 'pool', 'race', 'care', 'loop', 'alter', 'later'] print anagrams(input)
The output is
["alert", "alter", "later", "acre", "race", "care", "pool", "loop"]. The complexity of this solution seems to be O(n^2) (or very close to it) since we are iterating over each element twice - the outer loop picks an element, and then the inner loop goes over the remaining elements to find all matches; then the process repeats. I would like to think about a better approach in the future.
No comments :
Post a Comment