Skip to content

2605. Count Anagrams 👍

Group Anagrams | Count Ways to Build Rooms in an Ant Colony

Problem

You are given a string s containing one or more words. Every consecutive pair of words is separated by a single space ' '. A string t is an anagram of string s if the ith word of t is a permutation of the ith word of s.

  • For example, "acb dfe" is an anagram of "abc def", but "def cab" and "adc bef" are not.

Return the number of distinct anagrams of s. Since the answer may be very large, return it modulo 109 + 7.   Constraints:

  • 1 <= s.length <= 105

  • s consists of lowercase English letters and spaces ' '.

  • There is single space between consecutive words.

1
2
3
Input: s = "too hot"
Output: 18
Explanation: Some of the anagrams of the given string are "too hot", "oot hot", "oto toh", "too toh", and "too oht".
1
2
3
Input: s = "aa"
Output: 1
Explanation: There is only one anagram possible for the given string.

Complexity:

  • Time complexity : O(n).
  • Space complexity : O(n).

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from collections import Counter
from math import factorial
class Solution:
    """
    "too hot" => 3 x 6 => 18
    """
    def countAnagrams(self, s: str) -> int:
        res = 1
        for w in s.split(" "):
            cnt, prem = Counter(w), factorial(len(w))
            for rep in cnt.values():
                prem = prem // factorial(rep)
            res = res * prem % 1000000007
        return res
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * still incorrect with large numbers...
 */
var countAnagrams = function (s) {
    function factorial(n) {
        if (n === 0 || n === 1)
            return 1;
        else
            return n * factorial(n - 1);
    }
    // count of each word, too => {t: 1, o: 2}
    function helper(word) {
        const count = {};
        const n = word.length;
        for (let i = 0; i < n; i++) {
            (c = word[i]);
            count[c] = (count[c] || 0) + 1
        }
        const denomenator = Object.values(count).reduce((prod, x) => prod * factorial(x), 1);
        const numerator = factorial(n);
        return BigInt(numerator) / BigInt(denomenator);
    }
    let n = BigInt(1);
    const MODULO = BigInt(1000000007);
    s.split(" ").forEach(w => {
        console.log(helper(w));
        n *= helper(w);
    })
    return n % MODULO;
};