-
Notifications
You must be signed in to change notification settings - Fork 0
/
20210929_leetcode_group_anagrams.py
70 lines (45 loc) · 1.82 KB
/
20210929_leetcode_group_anagrams.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# 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,
# typically using all the original letters exactly once.
# Example 1:
# Input: strs = ["eat","tea","tan","ate","nat","bat"]
# Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
# Example 2:
# Input: strs = [""]
# Output: [[""]]
# Example 3:
# Input: strs = ["a"]
# Output: [["a"]]
# Constraints:
# 1 <= strs.length <= 104
# 0 <= strs[i].length <= 100
# strs[i] consists of lowercase English letters.
from typing import List
class Solution:
def groupAnagrams_I(self, strs: List[str]) -> List[List[str]]:
#brute force solution
#take each item sort to check their equality
#then add to a new nested list
#original list is popped
#TC: n^2, worst case
ans = []
while strs != []:
temp_i = strs.pop()
temp_lst = [temp_i]
temp_i = ''.join(sorted(temp_i))
for i in range(len(strs)-1, -1, -1):
#(n, 0) => [n-1, -1]
#going reverse will allow correct book keeping of the index
if len(strs[i]) != len(temp_i):
continue
if ''.join(sorted(strs[i])) == temp_i:
temp_lst.append(strs.pop(i))
ans.append(temp_lst)
return ans
def groupAnagrams_II(self, strs: List[str]) -> List[List[str]]:
#hashmap solution
ans = {}
for i in strs:
temp = ''.join(sorted(tuple(i))) #unique ordered key
ans[temp] = ans.get(temp, []) + [i] #values of the same key falls under the same key
return list(ans.values()) #output is a list