Reputation: 1220
I have an array that contains multiple words in there. The problem is asking me to find all the anagrams in there and pick out which one has the most anagrams. This is what I have so far:
For example: Before sorting, array has: [cat dog tac god act] then after that, it will have [act dgo act dgo act]
This approach seems to be good, but it depends on the number of the words that I have in the original array. If my original array is big enough, it could slow down the program due to copying process. Moreover, there is no way that I could keep track how many anagrams for each word. What could be the best approach to this kind of problem, consider that the array is big and the program has to find all the anagrams in a fast way ? Any help would be greatly appreciated. Thank you.
Upvotes: 1
Views: 588
Reputation: 77641
I think I would do something like this...
NSCountedSet
called anagramCounts
. The objects in here will be a sorted array of letters.anagramCounts
set.After doing this the anagramCounts
set will have all of the possible anagrams only once each and each will be stored next to a count of how many there are.
You can then get the object enumerator from this set and find the one with the highest count...
Or even... Add this to the previous list.
On the beginning
NSInteger
called highestAnagramCount
and set it to 0.NSArray
called mostCommonAnagram
and leave it as nil....
On the end
[anagramCounts countForObject:sortedArray];
and if it is higher than highestAnagramCount
then save this new value out and save the array.highestAnagramCount
will tell you how many anagrams there are and mostCommonAnagram
will contain the sorted array of letters.Upvotes: 1