Skip to content

Commit e026fa0

Browse files
Refactor group_anagrams to use character frequency as key
Replaced sorted strings with character frequency tuples as keys for grouping anagrams. This improves algorithm efficiency by avoiding repeated sorting operations for each word. The behavior of the function remains unchanged.
1 parent 898aa30 commit e026fa0

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

Arrays & Hashing/group_anagrams.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,16 @@ def group_anagrams(words: List[str]) -> List[List[str]]:
99
anagram_groups = defaultdict(list)
1010

1111
for word in words:
12-
sorted_word = "".join(sorted(word))
12+
# Create a character frequency tuple
13+
char_count = [0] * 26 # Assuming only lowercase letters
14+
for char in word:
15+
char_count[ord(char) - ord("a")] += 1
1316

14-
if sorted_word in anagram_groups:
15-
anagram_groups[sorted_word].append(word)
16-
continue
17+
# Use the tuple of counts as the key
18+
key = tuple(char_count)
19+
anagram_groups[key].append(word)
1720

18-
anagram_groups[sorted_word].append(word)
19-
20-
return [group for group in anagram_groups.values()]
21+
return list(anagram_groups.values())
2122

2223

2324
class Test(unittest.TestCase):

0 commit comments

Comments
 (0)