Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Group words that are anagrams of each other and report how many groups there are.

Problem: Group words that are anagrams of each other and report how many groups there are.
from collections import defaultdict
def groups(words):
    g = defaultdict(list)
    for w in words:
        g[''.join(sorted(w))].append(w)
    return len(g), max(len(v) for v in g.values())
print(groups(["listen", "silent", "enlist", "google", "gogole", "cat", "act", "tac", "dog"]))
What is printed?
  1. A. (3, 3)
  2. B. (4, 2)
  3. C. (4, 3)
  4. D. (5, 3)

Correct answer: C. (4, 3)

Sorted letters form the key: 'eilnst' (3 words), 'eggloo' (2), 'act' (3), 'dgo' (1) – 4 groups, largest size 3. Cost O(N · L log L) for N words of length L; a 26-count tuple key gives O(N · L).

More Coding Interview Problems questions

Exams that ask this topic