Data Structures & AlgorithmsModerateFlipkart/Uber OA · placement

Group words that are anagrams of each other using the sorted word as the key. What is printed?

Group words that are anagrams of each other using the sorted word as the key. What is printed?
from collections import defaultdict
g = defaultdict(list)
for w in ['god', 'enlist', 'listen', 'cat', 'silent', 'dog', 'tinsel', 'google']:
    g["".join(sorted(w))].append(w)
print(len(g), max(len(v) for v in g.values()))
  1. A. 4 3
  2. B. 6 4
  3. C. 4 4
  4. D. 2 5

Correct answer: C. 4 4

Anagrams share the same sorted letters, so they land in one bucket. Output (groups, largest group): 4 4.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic