Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an easy way to tell if a list of words are anagrams of each other?

How would you list words that are anagrams of each other?

I was asked this question when I applied for my current job.

orchestra can be rearranged into carthorse with all original letters used exactly once therefore the words are anagrams of each other.

like image 845
jqs Avatar asked Feb 06 '09 20:02

jqs


People also ask

How can you tell if two words are anagrams of each other?

Two words are anagrams of each other if they contain the same number of characters and the same characters. You should only need to sort the characters in lexicographic order, and determine if all the characters in one string are equal to and in the same order as all of the characters in the other string.

How do you check number is anagram or not?

Approach: Create two arrays freqA[] and freqB[] where freqA[i] and freqB[i] will store the frequency of digit i in a and b respectively. Now traverse the frequency arrays and for any digit i if freqA[i] != freqB[i] then the numbers are not anagrams of each other else they are.


2 Answers

Put all the letters in alphabetical order in the string (sorting algorithm) and then compare the resulting string.

like image 199
Adam Davis Avatar answered Sep 28 '22 04:09

Adam Davis


Good thing we all live in the C# reality of in-place sorting of short words on quad core machines with oozles of memory. :-)

However, if you happen to be memory constrained and can't touch the original data and you know that those words contain characters from the lower half of the ASCII table, you could go for a different algorithm that counts the occurrence of each letter in each word instead of sorting.

You could also opt for that algorithm if you want to do it in O(N) and don't care about the memory usage (a counter for each Unicode char can be quite expensive).

like image 44
Franci Penov Avatar answered Sep 28 '22 03:09

Franci Penov