Data Structures & AlgorithmsModerateTCS NQT · hashing

Problem: How many unordered pairs of words in ['abc', 'bca', 'xyz', 'cab'] are anagrams of each other? Run the code.

Problem: How many unordered pairs of words in ['abc', 'bca', 'xyz', 'cab'] are anagrams of each other? Run the code.
from itertools import combinations
words = ['abc', 'bca', 'xyz', 'cab']
print(sum(1 for a, b in combinations(words, 2) if sorted(a) == sorted(b)))
What is printed?
  1. A. 1
  2. B. 2
  3. C. 3
  4. D. 6

Correct answer: C. 3

'abc', 'bca' and 'cab' are mutual anagrams, giving C(3,2) = 3 pairs. 'xyz' matches none of them.

More Coding Interview Problems questions

Exams that ask this topic