Skip to content

Commit

Permalink
feature: group anagrams reduce revisit
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Dec 8, 2023
1 parent 29b8132 commit c4e5da2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
8 changes: 7 additions & 1 deletion arrays/GroupAnagrams.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import collections
from functools import reduce
from typing import List


# O(w * n * log(n)) time || O(wn) space
# O(w * n * log(n)) time || O(w * n) space
def group_anagrams(self, strs: List[str]) -> List[List[str]]:
dic = collections.defaultdict(list)

Expand All @@ -12,6 +13,11 @@ def group_anagrams(self, strs: List[str]) -> List[List[str]]:
return list(dic.values())


# O(w * n * log(n)) time || O(w * n) space
def group_anagrams_reduce(self, strs: List[str]) -> List[List[str]]:
return list(reduce(lambda acc, s: acc[tuple(sorted(s))].append(s) or acc, strs, collections.defaultdict(list)).values())


# O(n * m) time || O(n * m) space,
# m - number of strings
# n - average number of letters
Expand Down
5 changes: 4 additions & 1 deletion arrays/test/test_group_anagrams.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import unittest

from arrays.GroupAnagrams import group_anagrams, group_anagrams_count_approach
from arrays.GroupAnagrams import group_anagrams, group_anagrams_count_approach, group_anagrams_reduce


class MyTestCase(unittest.TestCase):
Expand All @@ -11,6 +11,9 @@ def test_group_anagrams(self):
self.assertEqual([['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']],
group_anagrams_count_approach(self, ["eat", "tea", "tan", "ate", "nat", "bat"]))

self.assertEqual([['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']],
group_anagrams_reduce(self, ["eat", "tea", "tan", "ate", "nat", "bat"]))


if __name__ == '__main__':
unittest.main()

0 comments on commit c4e5da2

Please sign in to comment.