Count Anagrams Problem
Description
LeetCode Problem 2514.
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 i^th word of t is a permutation of the i^th 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 10^9 + 7.
Example 1:
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".
Example 2:
Input: s = "aa"
Output: 1
Explanation: There is only one anagram possible for the given string.
Constraints:
1 <= s.length <= 10^5sconsists of lowercase English letters and spaces' '.- There is single space between consecutive words.
Solution
Approach: Multinomial Counting
A word of length L whose letters occur c1, c2, ... times has L! / (c1! * c2! * ...) distinct anagrams. The answer is the product of this over all words, modulo 10^9 + 7.
Process each word letter by letter. Multiply the numerator by the position i (building L!), and multiply the denominator by the running count of the current letter (building each c!). At the end divide by the denominator using a modular inverse (Fermat's little theorem, since the modulus is prime).
Complexity: O(n log mod) time, where n is the length of s, and O(1) space.
class Solution:
def countAnagrams(self, s: str) -> int:
mod = 10**9 + 7
ans = mul = 1
for w in s.split():
cnt = Counter()
for i, c in enumerate(w, 1):
cnt[c] += 1
mul = mul * cnt[c] % mod
ans = ans * i % mod
return ans * pow(mul, -1, mod) % mod