LeetCode solutions

2605. Count Anagrams

My accepted Python solution to LeetCode problem 2605, Count Anagrams, running in 692ms.

  • Difficulty: Hard
  • Python
  • Runtime 692ms
  • Memory 26MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 692ms, memory 26MB, accepted 2025-12-29.

python
class Solution:
    def countAnagrams(self, s: str) -> int:
        MOD = 10**9 + 7
        
        # Precompute factorials and inverse factorials
        MAX = 100001
        fact = [1] * MAX
        for i in range(1, MAX):
            fact[i] = fact[i-1] * i % MOD
        
        inv_fact = [1] * MAX
        inv_fact[MAX-1] = pow(fact[MAX-1], MOD-2, MOD)
        for i in range(MAX-2, -1, -1):
            inv_fact[i] = inv_fact[i+1] * (i+1) % MOD
        
        result = 1
        for word in s.split():
            n = len(word)
            # Count frequency of each character
            freq = {}
            for c in word:
                freq[c] = freq.get(c, 0) + 1
            
            # Number of permutations = n! / (freq1! * freq2! * ...)
            perms = fact[n]
            for f in freq.values():
                perms = perms * inv_fact[f] % MOD
            
            result = result * perms % MOD
        
        return result

Source