HardNo. 2514
Count Anagrams — LeetCode 2514 Python Solution
- Pattern
- Math and Number Theory
- Topics
- Hash Table, Math, String, Combinatorics, Counting
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a string s containing one or more words. Every consecutive pair of words is separated by a single space ' '.
Example
- Input
- s = "too hot"
- Output
- 18
- Explanation
- Some of the anagrams of the given string are "too hot", "oot hot", "oto toh", "too toh", and "too oht".
Python solution
class Solution:
def countAnagrams(self, s: str) -> int:
mod = 10**9 + 7
ans = mul = 1
for w in s.split():
cnt = Counter()
for i, c in enumerate(w, 1):
cnt[c] += 1
mul = mul * cnt[c] % mod
ans = ans * i % mod
return ans * pow(mul, -1, mod) % modComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2514. Count Anagrams is filed here because LeetCode tags it Math and Combinatorics, which is the vocabulary this hub collects.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 2842 | Count K-Subsequences of a String With Maximum Beauty | Hard |
| 2506 | Count Pairs Of Similar Strings | Easy |
| 0012 | Integer to Roman | Medium |
| 0013 | Roman to Integer | Easy |
| 0166 | Fraction to Recurring Decimal | Medium |
| 0299 | Bulls and Cows | Medium |
Frequently asked questions
- How hard is LeetCode 2514. Count Anagrams?
LeetCode 2514. Count Anagrams is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2514. Count Anagrams?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2514. Count Anagrams?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2514. Count Anagrams cover?
LeetCode 2514. Count Anagrams is tagged Hash Table, Math, String, Combinatorics and Counting on LeetCode.