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 - Optimal Solution INPUT Input String s: "ab" Character Analysis a b pos 0 pos 1 Single word: "ab" Length: 2 characters Unique chars: 2 s = "ab" (2 distinct letters) ALGORITHM STEPS 1 Split by spaces words = ["ab"] 2 Count permutations For each word: n! 3 Handle duplicates Divide by freq! 4 Multiply results Product mod 10^9+7 Formula for "ab": 2! / (1! * 1!) = 2 / 1 = 2 Permutations: "ab", "ba" Both are valid anagrams FINAL RESULT All distinct anagrams: "ab" "ba" Total Count: 2 OK - Answer verified Output: 2 (mod 10^9 + 7 = 2) Key Insight: For each word, anagrams = n! / (freq[c1]! * freq[c2]! * ... * freq[ck]!) Use modular inverse for division. Multiply results for all words. Use precomputed factorials for efficiency. TutorialsPoint - Count Anagrams | Optimal Solution (Combinatorics + Modular Arithmetic)
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