progress

~/problems / Counting / Combinatorics / inclusion-exclusion

Count distinct rearrangements of a string

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

Write count_arrangements(s: str) -> int: how many different strings can be made by reordering all the letters of s? Return the count mod 1_000_000_007.

Don't build the permutations. ⭐ Bonus: a speed test with a million-character s earns a star at about O(n) plus a few modular powers (huge exact factorials as Python big ints are too slow there).

count_arrangements("aabac")   # 20   (5! / (3! · 1! · 1!))
count_arrangements("abc")     # 6
count_arrangements("zzzz")    # 1
count_arrangements("x")       # 1

Constraints: 1 ≤ len(s) ≤ 10^6, s contains only a–z.

Show hint

Start from n! orderings of the positions and ask how many of them produce the same string when a letter repeats. Since the answer is taken mod a prime, replace each division by multiplication with a modular inverse (Fermat's little theorem gives one).

Topic: Combinatorics / inclusion-exclusion. Stars and bars, nCr identities, |A u B| = |A| + |B| - |A n B|.

0:00
Ctrl ' run · Ctrl ↵ submit
esc