The Count Anagrams interview question asks you to find the number of ways to rearrange a given string (which contains words separated by spaces) such that each word is an anagram of the original word. You only rearrange characters within each word; you do not change the order of the words themselves. You need to return the answer modulo 10^9 + 7.
MathWorks uses the Count Anagrams coding problem to test your knowledge of permutations of multi-sets and modular inverse. It’s a "Hard" problem because it involves complex formulas: n! / (n1! * n2! * ... * nk!), where ni is the frequency of each distinct character. You must perform division in modular arithmetic, which requires Fermat's Little Theorem.
This problem uses Combinatorics / Number Theory.
factorial(total_length) / product of factorial(frequencies).10^9 + 7, the division is performed by multiplying by the Modular Multiplicative Inverse.Input: "too hot"
t:1, o:2.
3! / (1! * 2!) = 6 / 2 = 3. (too, oto, oot)h:1, o:1, t:1.
3! / (1! * 1! * 1!) = 6.3 * 6 = 18.n! without dividing by the factorials of character frequencies./ with modulo, which is mathematically incorrect. You must use the modular inverse.Memorize the modular inverse formula: a^(p-2) % p where p is prime. This is essential for any combinatorics problem involving division and modulo.