-
Notifications
You must be signed in to change notification settings - Fork 40
/
group_anagrams.py
51 lines (41 loc) · 1.36 KB
/
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
#!/usr/bin/python
# Date: 2018-07-18
#
# Description:
# Write a method to sort an array of strings so that all the anagrams are next
# to each other.
#
# Approach:
# Sort strings to check if they are anagram of any previous string in array.
# And store all strings in a hash map, key will be sorted string and value will
# be list of original strings which is anagram of key.
#
# Complexity:
# M = Number of strings, N = Average length of strings.
# Time: O(M*N*log(N)), If sort_string takes N*log(N)
# Space: O(M*N) In worst case also.
#
# Improvement scope:
# We can implement counting sort to sort characters in a string, which has a
# time complexity of O(N) so overall complexity of this algorithm will be
# O(M*N).
import collections
def sort_string(s):
return ''.join(sorted(list(s)))
def group_anagrams(array):
hash_map = collections.defaultdict(list)
for s in array:
value = sort_string(s)
hash_map[value].append(s)
# Return grouped items - All values of hash map.
return [v for k in hash_map for v in hash_map[k]]
def main():
array = ['abc', 'adb', 'bac', 'bad', 'cat']
print(f'Input array of strings: {array}')
grouped = group_anagrams(array)
print(f'Anagrams grouped: {grouped}')
if __name__ == '__main__':
main()
# Output:
# Input array of strings: ['abc', 'adb', 'bac', 'bad', 'cat']
# Anagrams grouped: ['abc', 'bac', 'adb', 'bad', 'cat']