-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathGroup Anagrams.py
More file actions
35 lines (23 loc) · 988 Bytes
/
Copy pathGroup Anagrams.py
File metadata and controls
35 lines (23 loc) · 988 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""
Group Anagrams
Write a function that takes in array of strings and groups anagrams together
Anagrams are strings made up of exactly the same letters,where order doesn't matter.
For example, "cinema" and "iceman" are anagrams; similarly, "foo" and "ofo" are anagrams.
Your function should return a list of anagram groups in no particular order.
Sample Input
words = ["yo", "act", "flop", "tac", "foo", "cat", "oy", "olfp"]
Sample Output
[["yo","oy"], ["flop", "olfp"], ["act", "tac", "cat"], ["foo"]]
"""
# SOLUTION 1
# O(w * n * log(n) time | O(n) space - where w is the number of words
# where n is the length of the longest word.
def groupAnagrams(words):
anagrams = {}
for word in words:
sortedword = "".join(sorted(word))
if sortedword in anagrams:
anagrams[sortedword].append(word)
else:
anagrams[sortedword] = [word]
return list(anagrams.values())