I would like to get feedback on the solution and a question regarding Big O.
I am first converting each character in the string into the array and that would be O(n) then i am sorting the array O(n log n) and then I join back the array. Not sure if that is O(n). After i get the sorted string I would retrieve the NSArray from NSDictionary if it is there and either add the word to the array or create a new array and then set it back into the NSDictionary. I would those operations are O(1). The total runtime complexity is O(N log N) because of sort. Is that the correct breakdown.
void printAllAnagrams(NSArray *words)
{
NSMutableDictionary *anagramsDictionary = [[NSMutableDictionary alloc]init];
NSMutableArray *wordArray = [[NSMutableArray alloc]init];
for(NSString *word in words){
//Loop through each word
for(int i = 0;i < [word length]; i++){
//create a character array
[wordArray addObject:[NSString stringWithFormat:@"%c",[word characterAtIndex:i]]];
}
//sort character array
[wordArray sortUsingSelector:@selector(localizedCompare:)];
//convert character array back to string to use it as a key for in the dictionary
NSString *sortedString = [wordArray componentsJoinedByString:@""];
NSMutableArray *anagramStrings =[[anagramsDictionary objectForKey:sortedString] mutableCopy];
if(anagramStrings){
//if anagram(s) of the word is already in the dictionary then add this word to the array
//and store it back into the dictionary
[anagramStrings addObject:word];
[anagramsDictionary setObject:anagramStrings forKey:sortedString];
}else{
//create an array with current word and store it in the dictionary
//using the sorted characters string as the key
[anagramsDictionary setObject:@[word] forKey:sortedString];
}
[wordArray removeAllObjects];
}
NSLog(@"%@",anagramsDictionary);
}