Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate different anagrams

Suppose I have certain number of strings, say n, stored in random order in an array. A few, say m1, are anagrams of string1 and m2 are anagrams of string2 and so on. What would be an efficient algorithm to separate out strings that are anagrams of a particular string and determine the number of strings for each set?

like image 947
Bhavuk Mathur Avatar asked Apr 30 '26 02:04

Bhavuk Mathur


1 Answers

An interesting question. What we know about an anagram really boils down to 2 things.

  • they are the same length.
  • they are made up of the same characters.

determining the first condition is easy, the second, not so much. by first sorting the array of strings by length you limit the number of strings that you have to perform the 2nd test on.

The 2nd test appears to require that you not only check that string1.contains(string2[n]) but that you also determine that they occur the same number of times in each string. I would probably want a copy of the array of strings but I would make it an array of char[] because strings are immutable. Then I could sort each string in the copy by its component characters. Anagrams would now match with string1 == string2.

like image 185
John Faulkner Avatar answered May 02 '26 16:05

John Faulkner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!