#2514
Count Anagrams
HardHash TableMathStringCombinatoricsCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of generating permutations, we can calculate the number of distinct anagrams mathematically using factorials and the frequency of characters. This avoids the inefficiency of generating permutations and allows us to compute the result in linear time.
⚙️
Algorithm
5 steps- 1Step 1: Split the string into words.
- 2Step 2: For each word, count the frequency of each character.
- 3Step 3: Calculate the factorial of the length of the word.
- 4Step 4: Divide by the factorial of the frequency of each character to account for duplicates.
- 5Step 5: Multiply the results for all words and return the total modulo 10^9 + 7.
solution.py16 lines
1from collections import Counter
2from math import factorial
3
4MOD = 10**9 + 7
5
6def count_anagrams(s):
7 words = s.split()
8 total_anagrams = 1
9 for word in words:
10 freq = Counter(word)
11 word_length = len(word)
12 anagrams_count = factorial(word_length)
13 for count in freq.values():
14 anagrams_count //= factorial(count)
15 total_anagrams *= anagrams_count
16 return total_anagrams % MODℹ
Complexity note: The time complexity is O(n) because we traverse the string once to count characters and compute factorials. The space complexity is O(n) due to the storage of character frequencies.
- 1Understanding permutations requires knowledge of factorials.
- 2Character frequency is crucial for calculating distinct arrangements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.