LeetMotion
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.
"eat", "tea", and "ate" all sort to "aet". Use the sorted string as the hash map key. This takes O(k log k) per string where k is the string length.defaultdict(list). For each string, compute its sorted key and append the original string to map[key]. After processing all strings, return list(map.values()). Total: O(m · k log k) time, O(m · k) space, where m = number of strings, k = max string length.The naive approach: for every string, compare it against every other string by sorting both and checking equality. Group matched strings together.
s, scan all other strings and sort both to check if they are anagrams.def groupAnagrams(strs): groups, used = [], [False] * len(strs) for i in range(len(strs)): if used[i]: continue group = [strs[i]] for j in range(i + 1, len(strs)): if sorted(strs[i]) == sorted(strs[j]): group.append(strs[j]); used[j] = True groups.append(group) return groups
Two strings are anagrams if and only if their sorted strings are equal. We can iterate over the strings, sort each one to form a guaranteed unique key, and append it to our dictionary.
defaultdict(list).*Note: For absolute optimal performance O(m · k), you can count the 26 characters explicitly to act as the tuple key instead of sorting. The logic is structurally identical!
strsm strings, we sort it — sorting a string of length k costs O(k log k). Done once per string.k. Across all m strings this is O(m · k) — dominated by the sort step.m = number of strings and k = maximum string length. Space is O(m · k) to store all characters in the map.
Discussion
…