Skip to content

Commit ead9a9e

Browse files
author
Mauricio Klein
committed
Add solution for challenge #60
1 parent 1b02799 commit ead9a9e

File tree

6 files changed

+54
-0
lines changed

6 files changed

+54
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,4 @@
5959
- [x] [Challenge 57: Arithmetic Binary Tree](challenge-57/)
6060
- [x] [Challenge 58: Get all Values at a Certain Height in a Binary Tree](challenge-58/)
6161
- [x] [Challenge 59: Sort Colors](challenge-59/)
62+
- [x] [Challenge 60: Group anagrams](challenge-60/)

challenge-60/Makefile

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
test:
2+
python test_*.py
3+
4+
.PHONY: test

challenge-60/README.md

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Group anagrams
2+
3+
This problem was asked by RobinHood.
4+
5+
## Description
6+
7+
Given an array of strings, group anagrams together.
8+
9+
## Example
10+
11+
```
12+
Input: ['eat', 'ate', 'apt', 'pat', 'tea', 'now']
13+
Output: [
14+
['eat', 'ate', 'tea'],
15+
['apt', 'pat'],
16+
['now']
17+
]
18+
```

challenge-60/__init__.py

Whitespace-only changes.

challenge-60/solver.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#
2+
# Time complexity : O(n*klogk)
3+
# (where n = number of anagrams, k = length of the largest anagram)
4+
# (klogk because we sort every anagram once)
5+
# Space complexity: O(n)
6+
#
7+
def group_anagrams(anagrams):
8+
groups = {}
9+
10+
for word in anagrams:
11+
sorted_word = ''.join(sorted(word))
12+
13+
if sorted_word in groups:
14+
groups[sorted_word].append(word)
15+
else:
16+
groups[sorted_word] = [word]
17+
18+
return [g for g in groups.values()]

challenge-60/test_solver.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import unittest
2+
from solver import group_anagrams
3+
4+
class TestSolver(unittest.TestCase):
5+
def test_group_anagrams(self):
6+
anagrams = ['eat', 'ate', 'apt', 'pat', 'tea', 'now']
7+
expected_groups = [['eat', 'ate', 'tea'],
8+
['apt', 'pat'],
9+
['now']]
10+
self.assertItemsEqual(group_anagrams(anagrams), expected_groups)
11+
12+
if __name__ == "__main__":
13+
unittest.main()

0 commit comments

Comments
 (0)