This notebook was prepared by Donne Martin. Source and license info is on GitHub.

Challenge Notebook

Problem: Sort an array of strings so all anagrams are next to each other.


  • Are there any other sorting requirements other than the grouping of anagrams?
    • No
  • Can we assume the inputs are valid?
    • No
  • Can we assume this fits memory?
    • Yes

Test Cases

  • None -> Exception
  • [] -> []
  • General case
    • Input: ['ram', 'act', 'arm', 'bat', 'cat', 'tab']
    • Result: ['arm', 'ram', 'act', 'cat', 'bat', 'tab']


Refer to the Solution Notebook. If you are stuck and need a hint, the solution notebook's algorithm discussion might be a good place to start.


In [ ]:
from collections import OrderedDict

class Anagram(object):

    def group_anagrams(self, items):
        # TODO: Implement me

Unit Test

The following unit test is expected to fail until you solve the challenge.

In [ ]:
# %load
import unittest

class TestAnagrams(unittest.TestCase):

    def test_group_anagrams(self):
        anagram = Anagram()
        self.assertRaises(TypeError, anagram.group_anagrams, None)
        data = ['ram', 'act', 'arm', 'bat', 'cat', 'tab']
        expected = ['ram', 'arm', 'act', 'cat', 'bat', 'tab']
        self.assertEqual(anagram.group_anagrams(data), expected)

        print('Success: test_group_anagrams')

def main():
    test = TestAnagrams()

if __name__ == '__main__':

Solution Notebook

Review the Solution Notebook for a discussion on algorithms and code solutions.