Count Anagrams — LeetCode 2514 Python Solution

HardHash TableMathStringCombinatoricsCounting
Problem
#2514
Reading time
2 min

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

Python
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) % mod

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview