Data Structures & AlgorithmsModerateTCS NQT · string counting

Problem: How many distinct palindromes can be formed by rearranging the letters of 'aabb' (distinct strings, all letters used)? Run the code.

Problem: How many distinct palindromes can be formed by rearranging the letters of 'aabb' (distinct strings, all letters used)? Run the code.
from itertools import permutations
s = 'aabb'
print(len({p for p in map(''.join, permutations(s)) if p == p[::-1]}))
What is printed?
  1. A. 1
  2. B. 2
  3. C. 4
  4. D. 0

Correct answer: B. 2

The palindromes are abba and baab. A palindrome needs at most one odd-count letter, and here both letters have even counts, so both arrangements work.

More Coding Interview Problems questions

Exams that ask this topic