Group Anagrams
Definition
A word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.
Valid Anagram (LC.242)
Given two strings, determine if they are anagrams.
Example
("anagram", "nagaram") => true
("rat", "car") => falseApproach 1
let N = len(word1) + len(word2) Sort then compare O(Nlog(N)) + O(N)
public boolean isAnagram(String word1, String word2) {
if (word1.length() != word2.length()) {
return false;
}
char[] arr1 = word1.toCharArray();
char[] arr2 = word2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}Approach 2
Use a hashtable then count O(N) + O(N)
Group Anagrams (LC.49)
Given an array of words, return a list of lists of anagrams.
Example
Brute Force Approach
For each word in the list, we try to find its group by checking with the rest of the list. Keep a visited array so we don't visit the word more than once.
Let N be the number of words, K be the maximum length of a word.
The time complexity is O(N) (outer loop) * O(N) (inner loop worst case compare against the rest) * O(2K) (hashtable + compare) = O(KN^2). This will pass 100 / 101 test cases on LC. How can we do better?
Sorting and Hashing
We can optimized to the inner loop to O(K) by hashing the sorted word. If the hashmap contains the word then we add it to the result list. If not, we want to put (sortedWord, sortedWord) to the map.
Time complexity O(NKlogK) Space complexity O(NK)
Last updated