Count Anagrams - 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 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.

Input & Output

Example 1 — Basic Case
$ Input: s = "ab"
Output: 2
💡 Note: The word "ab" can be rearranged as "ab" and "ba", giving us 2 distinct anagrams.
Example 2 — Two Words
$ Input: s = "ab cd"
Output: 4
💡 Note: Word "ab" has 2 permutations: "ab", "ba". Word "cd" has 2 permutations: "cd", "dc". Total anagrams = 2 × 2 = 4.
Example 3 — Repeated Characters
$ Input: s = "aab"
Output: 3
💡 Note: The word "aab" can be arranged as "aab", "aba", "baa". Using formula: 3! / 2! = 6 / 2 = 3.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s contains only lowercase English letters and spaces
  • s does not have leading or trailing spaces
  • Every consecutive pair of words is separated by a single space

Visualization

Tap to expand
Count Anagrams: Input → Process → OutputINPUT"aab cd"Two words separatedPROCESS"aab": 3!/2! = 3"cd": 2!/1!/1! = 2OUTPUT3 × 2 = 6Total anagramsExamples of the 6 anagrams:"aab cd", "aba cd", "baa cd", "aab dc", "aba dc", "baa dc"
Understanding the Visualization
1
Input
String with words separated by spaces
2
Process
Calculate anagram count for each word using mathematical formula
3
Output
Product of all word anagram counts
Key Takeaway
🎯 Key Insight: Use the permutation formula n! / (product of factorial of frequencies) to avoid generating actual permutations
Asked in
Google 12 Facebook 8
12.5K Views
Medium Frequency
~25 min Avg. Time
450 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