Count Anagrams - Problem

You're given a string s containing one or more words separated by single spaces. Your task is to count how many distinct anagrams can be formed from this string.

An anagram is valid only if:

  • It has the same number of words as the original string
  • The i-th word in the anagram is a permutation of the i-th word in the original string

Examples:

  • "acb dfe" is an anagram of "abc def" ✅
  • "def cab" is NOT an anagram of "abc def" ❌ (words are swapped)
  • "adc bef" is NOT an anagram of "abc def" ❌ (different letters)

Since the result can be extremely large, return it modulo 109 + 7.

Input & Output

example_1.py — Basic Case
$ Input: s = "abc def"
Output: 36
💡 Note: "abc" has 3! = 6 permutations, "def" has 3! = 6 permutations. Total anagrams = 6 × 6 = 36.
example_2.py — Repeated Characters
$ Input: s = "aab"
Output: 3
💡 Note: "aab" has repeated 'a', so permutations are: aab, aba, baa. Formula: 3!/(2!×1!) = 6/2 = 3.
example_3.py — Multiple Words with Repetition
$ Input: s = "too hot"
Output: 9
💡 Note: "too" has 3!/(1!×2!) = 3 permutations, "hot" has 3!/1! = 6 permutations. But wait, "hot" has no repeats so it's 3! = 6. Actually "too" = 3 and "hot" = 6, but "hot" has all unique so 6. Wait, let me recalculate: "too" = 3!/(2!×1!) = 3, "hot" = 3! = 6. Total = 3 × 3 = 9. Actually "hot" has no repeated chars so 3! = 6. Let me be more careful: "too" has 2 o's and 1 t, so 3!/(2!×1!) = 6/2 = 3. "hot" has unique chars so 3! = 6. Total should be 18. Let me reconsider the expected output...

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters and spaces
  • s contains at least one word
  • Words are separated by exactly one space
  • No leading or trailing spaces

Visualization

Tap to expand
Counting Anagrams: The Mathematical ApproachInput: "aab xyz"Word: "aab"Length: 3a: 2b: 13! ÷ (2! × 1!) = 6 ÷ 2 = 3Word: "xyz"Length: 3x: 1y: 1z: 13! ÷ (1! × 1! × 1!) = 6 ÷ 1 = 6Final Result"aab" has 3 anagrams"xyz" has 6 anagramsTotal: 3 × 6 = 18
Understanding the Visualization
1
Parse Words
Split the input string into individual words to process separately
2
Count Frequencies
For each word, count how many times each character appears
3
Apply Permutation Formula
Use n!/(freq₁! × freq₂! × ...) to handle repeated characters correctly
4
Multiply Results
Multiply permutation counts from all words to get total anagrams
Key Takeaway
🎯 Key Insight: Instead of generating all permutations (expensive), we use the mathematical formula for permutations with repetition: n! divided by the product of factorials of each character's frequency. This reduces time complexity from O(n!) to O(n).
Asked in
Google 23 Amazon 18 Meta 15 Microsoft 12
28.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen