Count Subsequences With Uniform Letter Frequency
Math & Bit ManipulationAuto-graded · 22 test casesLast updated
Tests combinatorics, modular arithmetic, and frequency grouping by counting index-distinct subsequences where every included letter appears the same number of times.
Count Subsequences With Uniform Letter Frequency
A subsequence is any selection of characters from a string that preserves their relative order (including the selection that keeps all characters, or the one that keeps just one). Two selections are considered distinct whenever they differ in which positions were chosen, even if the resulting strings look identical.
Call a non-empty subsequence balanced when every letter that appears in it occurs exactly the same number of times as every other letter that appears in it. For example, picking one a and one b is balanced; picking two as and one b is not.
Given a string word of lowercase English letters, return the total number of balanced subsequences modulo 1_000_000_007.
Constraints
1 <= len(word) <= 100_000wordconsists of lowercase English letters only (a–z)- The empty selection is not considered balanced and must not be counted
- Two subsequences that use different sets of positions count separately, regardless of whether they spell the same string
- Return the result modulo
1_000_000_007
Examples
Example 1
Input: count_balanced_subsequences('abca')
Output: 12
Example 2
Input: count_balanced_subsequences('abcd')
Output: 15
Hints
Hint 1
Group balanced subsequences by their shared frequency f (the number of times each chosen letter appears). Every balanced subsequence belongs to exactly one group, so you can sum the counts across all valid values of f without double-counting.
Hint 2
For a fixed target frequency f, each letter independently contributes a factor of (1 + C(occurrences, f)): either you skip that letter entirely (1 way) or you pick exactly f of its positions (C(occurrences, f) ways). Multiply these factors across all 26 letters to get the number of selections for this f, then subtract 1 to remove the all-skipped empty selection.
Hint 3
Computing C(n, k) naively inside a loop is too slow for n up to 100 000. Precompute a factorial table and its modular inverse (one Fermat inversion with pow(factorial[n], MOD-2, MOD), then fill the rest downward) so each binomial coefficient costs O(1).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Decompose by shared frequency
Every balanced subsequence has a single well-defined shared frequency f: the exact number of times each of its letters appears. That value is unique to the subsequence, so partitioning by f produces non-overlapping groups that together cover every balanced subsequence. Summing over all possible values of f therefore counts each one exactly once.
Count selections for a fixed f
Fix a target frequency f. For each letter c with occurrences[c] positions in word, there are two independent choices:
- Skip the letter entirely: 1 way.
- Include it at exactly
fpositions:C(occurrences[c], f)ways.
Because letters are independent of one another, the total number of selections for this f is:
product over all 26 letters of (1 + C(occurrences[c], f))
This product counts one selection where every letter is skipped — the empty selection. Subtracting 1 removes it, leaving only non-empty balanced selections with shared frequency f.
The final answer is:
sum over f from 1 to max(occurrences) of (product - 1)
Why there is no double-counting
A balanced subsequence with shared frequency f picks, for each of its letters, exactly f positions. That means it shows up in exactly the f-th term of the sum and nowhere else. The product structure ensures every such selection is represented exactly once within each term.
Computing binomial coefficients efficiently
With n up to 100 000, computing C(n, k) by Pascal's triangle would require an O(n²) table, which is too large. Instead, precompute:
factorial[i] = i! mod MODin a single upward pass.inv_factorial[n] = (n!)^(MOD-2) mod MODusing Fermat's little theorem (onepowcall).- The remaining inverse factorials via the downward recurrence
inv_factorial[i-1] = inv_factorial[i] * i % MOD.
Each C(total, chosen) then costs O(1): factorial[total] * inv_factorial[chosen] * inv_factorial[total - chosen] mod MOD.
Complexity
- Time: O(n + 26 · max_count). Counting letters and building the factorial tables are both O(n). The main loop runs at most
max_count ≤ niterations, each doing 26 O(1) binomial evaluations — roughly 2.6 million cheap operations for the maximum input size. - Space: O(n) for the factorial and inverse-factorial tables, plus O(26) for the letter counts.
Edge cases
- Single character
"z":f = 1gives(1 + 1) - 1 = 1. Correct: the only balanced subsequence is the single character itself. - All identical letters, e.g.
"aaaa": every non-empty subsequence is balanced. The formula yieldssum over f of C(4, f) = 2^4 - 1 = 15. - All distinct letters: every non-empty subsequence is balanced (each letter appears once). Only
f = 1contributes:2^n - 1. - Modular subtraction: subtracting 1 from a product that is 0 mod MOD would give -1 in languages without Python's non-negative
%. In Python(answer + ways - 1) % MODis always safe.
Reference solution
from typing import List
MOD = 1_000_000_007
def count_balanced_subsequences(word: str) -> int:
# Count how many times each of the 26 letters appears.
counts = [0] * 26
for ch in word:
counts[ord(ch) - ord('a')] += 1
# Precompute factorial and inverse-factorial tables for O(1) binomials.
n = len(word)
factorial = [1] * (n + 1)
for i in range(1, n + 1):
factorial[i] = factorial[i - 1] * i % MOD
inv_factorial = [1] * (n + 1)
inv_factorial[n] = pow(factorial[n], MOD - 2, MOD) # Fermat's little theorem
for i in range(n, 0, -1):
inv_factorial[i - 1] = inv_factorial[i] * i % MOD
def combinations(total: int, chosen: int) -> int:
if chosen < 0 or chosen > total:
return 0
return (
factorial[total]
* inv_factorial[chosen]
% MOD
* inv_factorial[total - chosen]
% MOD
)
answer = 0
maximum = max(counts)
for frequency in range(1, maximum + 1):
# For this target frequency, each letter either contributes 0 or exactly
# `frequency` positions. Multiply the independent per-letter factors.
ways = 1
for count in counts:
ways = ways * (1 + combinations(count, frequency)) % MOD
# Subtract 1 to remove the all-skipped (empty) selection for this frequency.
answer = (answer + ways - 1) % MOD
return answer