Subsequences With Uniform Letter Counts
Medium · Coding & Algorithms · Machine Learning Engineer · Online Assessment
Problem Statement
Given a string word of lowercase English letters, pick one or more character indices and read their characters from left to right in their original relative order to form a non-empty subsequence. Two selections that choose different index sets always count as separate subsequences, even when they spell identical strings.
Call a non-empty subsequence balanced if every distinct letter appearing in that subsequence occurs the exact same number of times. Compute how many balanced subsequences can be formed from word, and return the count modulo 1_000_000_007 (10^9 + 7).
def count_good_subsequences(word: str) -> int:
Examples
Example 1
Input: word = "xyyxz"
Output: 20
Walk-through:
- Letters 'x' and 'y' each occur twice ({0, 3} and {1, 2}), while 'z' occurs once ({4}).
- With 1 copy per included letter: each of 'x' and 'y' has 3 options (omit, first index, or second index) and 'z' has 2 options (omit or index 4), yielding 3 * 3 * 2 - 1 = 17 non-empty index sets.
- With 2 copies per included letter: 'z' must be omitted, while 'x' and 'y' each either stay out or contribute both of their indices, yielding 2 * 2 - 1 = 3 non-empty index sets ("xx", "yy", and "xyyx").
- Summing both groups gives 17 + 3 = 20.
Example 2
Input: word = "cat"
Output: 7
Walk-through:
- Because 'c', 'a', and 't' each appear only once, every non-empty choice of indices includes each selected letter once, giving all 2^3 - 1 = 7 non-empty subsequences.
Constraints
1 <= len(word) <= 100_000wordconsists only of lowercase ASCII letters ('a'through'z').- The empty selection of zero characters is excluded.
- Distinct index subsets are counted separately regardless of the text they spell.
- Return the result modulo
1_000_000_007.
Step-by-step walkthrough
Restate the problem and what counts as a subsequence
A subsequence is a selection of index positions from
word, read left to right in their original relative order. Importantly, two distinct index selections count as two distinct subsequences even when they spell the exact same string.A non-empty subsequence is balanced if every distinct letter inside it occurs the exact same number of times:
word = "xyyxz" (indices: 0:'x', 1:'y', 2:'y', 3:'x', 4:'z') Balanced examples: indices {0} -> "x" (x: 1) valid indices {3} -> "x" (x: 1) valid (separate index choice!) indices {0, 3} -> "xx" (x: 2) valid indices {0, 1, 2, 3} -> "xyyx" (x: 2, y: 2) valid indices {0, 2, 4} -> "xyz" (x: 1, y: 1, z: 1) valid Unbalanced / invalid examples: indices {} -> "" (empty is excluded) indices {0, 1, 3} -> "xyx" (x: 2, y: 1 -> unequal counts!)Given
wordof lengthnup to100,000, we want the number of balanced subsequences modulo1_000_000_007.Why listing every subsequence is too slow
At each of the
nindices, we either include or skip that position. That gives2^n - 1non-empty index subsets:for each non-empty subset of indices 0 .. n - 1: count how many times each chosen letter appears if all chosen letters have the same count: answer += 1For
n = 10(2^10 - 1 = 1,023), this brute-force check finishes instantly and serves as our test oracle. Forn = 100,000,2^100,000exceeds 30,000 decimal digits, so we must count valid index subsets combinatorially rather than enumerating them.Key idea: group subsequences by their shared frequency k
In any balanced subsequence, every included letter appears some positive number of times
k(k = 1,k = 2, ..., up to the largest single-letter count inword). Because each non-empty balanced subsequence has a unique shared countk, partitioning byksplits the answer into disjoint buckets:- Bucket
k = 1: subsequences where every included letter appears 1 time. - Bucket
k = 2: subsequences where every included letter appears 2 times. - ... up to
max_freq.
Once
kis fixed, distinct letters are completely independent. Why? Because a subsequence is uniquely determined by which set of indices we pick: choosing positions holding'x'never collides with positions holding'y', and reading the union of chosen indices left to right automatically preservesword's order!Suppose a letter occurs
freqtimes inword. When building a bucket-ksubsequence, what choices exist for that letter?Letter with `freq` copies in `word`: Option 1: Omit this letter altogether -> 1 way Option 2: Pick exactly k of its `freq` copies -> C(freq, k) ways (0 ways if freq < k) ------------------------------------------------------------------------- Total independent options for this letter = 1 + C(freq, k)Multiplying
(1 + C(freq, k))across all distinct letters counts every subset where each letter appears0orktimes. Exactly one of those combinations omits every single letter (the empty subsequence). Subtracting1leaves the exact count for bucketk:ways(k) = ( product over all distinct letters of (1 + C(freq, k)) ) - 1Notice that character order in
worddrops out completely — only each letter's total countfreqmatters!- Bucket
Precompute combinations C(f, k) modulo 1,000,000,007
The binomial formula
C(f, k) = f! / (k! * (f - k)!)divides by factorials. Under modular arithmetic (MOD = 1_000_000_007), integer division//does not work on remainders; instead, we multiply by the modular inverse — the numberinvsatisfying(x * inv) % MOD == 1.Because
MOD = 1_000_000_007is prime andn <= 100,000 < MOD, none of1!, 2!, ..., n!is a multiple ofMOD. By Fermat's little theorem,x^(MOD - 2) % MODequals the modular inverse ofx.Even better, instead of calling
pow()ntimes, we invertn!once viapow(fact[n], MOD - 2, MOD)and step down fromnto1using1 / (i - 1)! = i / i!:# Phase 1: Precompute factorials and inverse factorials modulo MOD so C(f, k) takes O(1) time. # fact[i] stores i! % MOD, e.g. [1, 1, 2, 6, 24, ...] fact = [1] * (n + 1) for i in range(1, n + 1): fact[i] = (fact[i - 1] * i) % MOD # inv_fact[i] stores (i!)^(-1) % MOD, satisfying (fact[i] * inv_fact[i]) % MOD == 1. # Because MOD = 1_000_000_007 is prime and n < MOD, x^(MOD - 2) % MOD is x^(-1) by Fermat's little theorem. inv_fact = [1] * (n + 1) inv_fact[n] = pow(fact[n], MOD - 2, MOD) # Walk down from n to 1 using 1/(i - 1)! = i / i! so we call pow() once instead of n times. for i in range(n, 0, -1): inv_fact[i - 1] = (inv_fact[i] * i) % MOD def choose(total_copies: int, pick_count: int) -> int: # C(total_copies, pick_count) = total_copies! / (pick_count! * (total_copies - pick_count)!) mod MOD numerator = fact[total_copies] denominator_inv = (inv_fact[pick_count] * inv_fact[total_copies - pick_count]) % MOD return (numerator * denominator_inv) % MODAfter this
O(n)setup, everychoose(freq, k)lookup runs inO(1)time.Keep the loop over k linear by sorting frequencies
Whenever a letter has
freq < k, it cannot contributekcopies, so its factor is1 + 0 = 1. Multiplying a product by1leaves it unchanged.Sorting
sorted_freqsin descending order lets usbreakout of the inner loop at the very first letter withfreq < k. Watch which(letter, k)pairs are visited on"abbccc"(sorted_freqs = [3, 2, 1]):word = "abbccc" -> sorted_freqs = [3, 2, 1] (sum of frequencies = 6) k = 3: [c:3] -> 1 letter processed (stops at b: 2 < 3) k = 2: [c:3] [b:2] -> 2 letters processed (stops at a: 1 < 2) k = 1: [c:3] [b:2] [a:1] -> 3 letters processed ----------------- Total inner-loop multiplications = 1 + 2 + 3 = 6 = len(word)!Each letter with count
freqis visited only fork = 1, 2, ..., freq. Across all outer iterations, the inner loop performssum(sorted_freqs) = nmultiplications in total — linear inlen(word)regardless of alphabet size!# Phase 2: Count each distinct letter and sort frequencies from largest to smallest. char_counts: Dict[str, int] = {} for ch in word: char_counts[ch] = char_counts.get(ch, 0) + 1 sorted_freqs = sorted(char_counts.values(), reverse=True) max_freq = sorted_freqs[0] # Phase 3: Group balanced subsequences by their shared character count k (1 .. max_freq). total_good = 0 for k in range(1, max_freq + 1): ways_for_k = 1 for freq in sorted_freqs: if freq < k: break choices_for_letter = 1 + choose(freq, k) ways_for_k = (ways_for_k * choices_for_letter) % MOD non_empty_ways = (ways_for_k - 1) % MOD total_good = (total_good + non_empty_ways) % MODNote on
(ways_for_k - 1) % MOD: ifways_for_kwraps around to0moduloMOD,ways_for_k - 1is-1. Python's% MODmaps-1toMOD - 1(0 .. MOD - 1), whereas in C++ or Java you would write(ways_for_k - 1 + MOD) % MOD.Trace Example 1 step by step
Let's trace
word = "xyyxz"(n = 5):Letter counts: 'x': 2, 'y': 2, 'z': 1 sorted_freqs = [2, 2, 1], max_freq = 2 --- k = 1 --- freq = 2 ('x'): choices = 1 + C(2, 1) = 1 + 2 = 3 -> ways_for_k = 3 freq = 2 ('y'): choices = 1 + C(2, 1) = 1 + 2 = 3 -> ways_for_k = 9 freq = 1 ('z'): choices = 1 + C(1, 1) = 1 + 1 = 2 -> ways_for_k = 18 non_empty_ways = 18 - 1 = 17 (all non-empty subsets using at most 1 of each letter) --- k = 2 --- freq = 2 ('x'): choices = 1 + C(2, 2) = 1 + 1 = 2 -> ways_for_k = 2 freq = 2 ('y'): choices = 1 + C(2, 2) = 1 + 1 = 2 -> ways_for_k = 4 freq = 1 ('z'): 1 < 2 -> break! non_empty_ways = 4 - 1 = 3 ("xx" {0,3}, "yy" {1,2}, and "xyyx" {0,1,2,3}) Total = 17 + 3 = 20For Example 2 (
word = "cat"),sorted_freqs = [1, 1, 1], so onlyk = 1runs:2 * 2 * 2 - 1 = 7.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple MOD = 1_000_000_007 def count_good_subsequences(word: str) -> int: n = len(word) if n == 0: return 0 # Phase 1: Precompute factorials and inverse factorials modulo MOD so C(f, k) takes O(1) time. # fact[i] stores i! % MOD, e.g. [1, 1, 2, 6, 24, ...] fact = [1] * (n + 1) for i in range(1, n + 1): fact[i] = (fact[i - 1] * i) % MOD # inv_fact[i] stores (i!)^(-1) % MOD, satisfying (fact[i] * inv_fact[i]) % MOD == 1. # Because MOD = 1_000_000_007 is prime and n < MOD, x^(MOD - 2) % MOD is x^(-1) by Fermat's little theorem. inv_fact = [1] * (n + 1) inv_fact[n] = pow(fact[n], MOD - 2, MOD) # Walk down from n to 1 using 1/(i - 1)! = i / i! so we call pow() once instead of n times. for i in range(n, 0, -1): inv_fact[i - 1] = (inv_fact[i] * i) % MOD def choose(total_copies: int, pick_count: int) -> int: # C(total_copies, pick_count) = total_copies! / (pick_count! * (total_copies - pick_count)!) mod MOD numerator = fact[total_copies] denominator_inv = (inv_fact[pick_count] * inv_fact[total_copies - pick_count]) % MOD return (numerator * denominator_inv) % MOD # Phase 2: Count each distinct letter and sort frequencies from largest to smallest. # char_counts: maps letter -> total occurrences in word, e.g. {"x": 2, "y": 2, "z": 1} char_counts: Dict[str, int] = {} for ch in word: char_counts[ch] = char_counts.get(ch, 0) + 1 # sorted_freqs: frequencies in descending order, e.g. [2, 2, 1] for "xyyxz" sorted_freqs = sorted(char_counts.values(), reverse=True) max_freq = sorted_freqs[0] # Phase 3: Group balanced subsequences by their shared character count k (1 .. max_freq). total_good = 0 for k in range(1, max_freq + 1): # ways_for_k counts subsets where every distinct letter appears either 0 times or k times. ways_for_k = 1 for freq in sorted_freqs: # Because sorted_freqs is descending, once freq < k, this letter and all remaining # letters lack k copies and only have the 1 option of staying out (multiplying by 1). if freq < k: break # A letter with `freq` copies either stays out (1 way) or contributes `k` chosen indices. choices_for_letter = 1 + choose(freq, k) ways_for_k = (ways_for_k * choices_for_letter) % MOD # Subtract 1 to exclude the empty subsequence where every letter chose to stay out. non_empty_ways = (ways_for_k - 1) % MOD total_good = (total_good + non_empty_ways) % MOD return total_good✅ Submit now — all tests should pass.
Intuition & how it works
Imagine you have jars of colored marbles — say 2 red marbles, 2 blue marbles, and 1 green marble — where every marble has a unique ID sticker, and you want to assemble non-empty gift bags in which every color placed inside the bag appears the exact same number of times k. A subsequence (a subset of character indices kept in their original left-to-right order) works just like that gift bag: once you choose which index positions to keep for each letter, there is only one left-to-right order in which they appear in word.
The naive approach tries all 2^n - 1 non-empty subsets of indices and checks whether the chosen letters share one frequency. While fast for 10 characters, 2^100,000 has over 30,000 digits, so enumerating subsets one by one will never finish. Even left-to-right dynamic programming stalls because tracking all 26 letter counts simultaneously blows up the state space.
Instead, we partition valid subsequences by their shared per-letter count k (k = 1, k = 2, and so on). For a fixed k, each letter with f copies in word makes an independent decision: either stay out completely (1 way) or contribute k of its f index positions (C(f, k) ways, where the binomial coefficient C(f, k) is the number of ways to pick k items out of f regardless of order). Multiplying (1 + C(f, k)) across letters and subtracting 1 (the empty bag where every letter stayed out) counts bucket k in one pass!
Walk through Example 1, word = "xyyxz" ('x' appears 2 times, 'y' appears 2 times, 'z' appears 1 time):
1. k = 1 (1 of each included letter): 'x' has 1 + C(2, 1) = 3 options, 'y' has 1 + C(2, 1) = 3 options, and 'z' has 1 + C(1, 1) = 2 options. That gives 3 * 3 * 2 - 1 = 17 non-empty subsequences.
2. k = 2 (2 of each included letter): 'x' and 'y' each have 1 + C(2, 2) = 2 options (skip, or pick both copies), while 'z' has fewer than 2 copies and must stay out (1 option). That gives 2 * 2 - 1 = 3 subsequences ("xx", "yy", and "xyyx").
3. Summing the disjoint buckets gives 17 + 3 = 20.
To prevent giant integers, we use modular arithmetic (keeping remainders modulo MOD = 1_000_000_007 at each step). Because division does not apply directly to remainders, we multiply by the modular multiplicative inverse (the number inv satisfying (x * inv) % MOD == 1), computed via Fermat's little theorem (which guarantees x^(MOD - 2) % MOD is the inverse of x whenever MOD is prime and does not divide x).
Complexity
Let n be the length of word and d be the number of distinct characters (d <= 26 for lowercase English letters).
- Time:
O(n + d log d), which simplifies toO(n)for lowercase letters. Counting characters and building thefactandinv_facttables each scannelements once (O(n)), with a singlepow(..., MOD - 2, MOD)call takingO(log MOD)(~30) multiplications. Sorting thedcharacter counts takesO(d log d). Finally, because frequencies are sorted descending and the inner loop breaks as soon asfreq < k, each letter with frequencyfreqis visitedfreqtimes across allk, so the nested loop performssum(freq) = nmultiplications plus at mostnbreak checks overall. - Space:
O(n). We store two arrays (factandinv_fact) of lengthn + 1, plus a frequency dictionary of at mostd <= 26entries.
Edge cases
- Single character (
"a"): Onlyk = 1runs, giving(1 + 1) - 1 = 1. - One letter repeated
ntimes ("aaaa..."): Every non-empty subset of indices uses only that one letter and therefore qualifies, summing to(2^n - 1) % MOD. - All letters distinct (
"cat"or the 26-letter alphabet):max_freq = 1, so onlyk = 1runs and every non-empty subsequence qualifies (2^n - 1). - Identical strings from different indices (
"xyyxz"): Picking'x'at index 0 and picking'x'at index 3 are two separate subsequences;C(2, 1) = 2counts both automatically. - Huge intermediate counts (
n = 100,000): True counts can exceed2^100,000, so reducing% MODafter every multiplication and addition avoids slow arbitrary-precision integers.
Common mistakes
- Deduplicating subsequence strings instead of counting index sets:
"xyyxz"produces duplicate strings like"x"from index0and index3, so string deduplication undercounts valid index subsets. - Subtracting
1only once at the very end instead of once perk: Everykiteration includes its own "all letters stay out" empty option inways_for_k, so1must be subtracted for eachk. - Calling
math.comb(freq, k)inside the loop: Atn = 100,000,math.comb(100_000, k)builds exact 30,000-digit integers tens of thousands of times and times out; modular factorial tables keep every value under10^9 + 7. - Breaking on
freq < kwithout sorting frequencies descending first: On"abbccc"with unsorted counts[1, 2, 3], breaking when1 < 2skips'b'and'c'fork = 2andk = 3, returning23instead of31. - Negative modulo in C++ or Java: When
ways_for_kequals0moduloMOD,ways_for_k - 1is-1. Python's% MODwraps-1toMOD - 1, whereas C++ and Java preserve-1unless you write(ways_for_k - 1 + MOD) % MOD.
Alternative approaches
- Scan all 26 letters per
kwithout sorting or breaking: With at most 26 lowercase letters, checking every present letter for eachk = 1 .. max_freqperforms at most26 * nsteps (~2.6 * 10^6operations), which also passes ford <= 26— though sorting + breaking is cleaner and staysO(n)even on unbounded alphabets. - Pascal's triangle table for
C(f, k): ComputingC(f, k) = (C(f - 1, k - 1) + C(f - 1, k)) % MODavoids modular inverses for smalln(n <= 2,000), but takesO(n^2)time and memory (~10^10cells atn = 100,000).
Follow-up questions
- How would you adjust the count if a valid subsequence had to include at least two distinct letters? Any non-empty subsequence formed from copies of a single letter (
2^freq - 1index choices) automatically has uniform letter counts, and those are the exact cases that violate the two-letter rule. Subtract(pow(2, freq, MOD) - 1)for each distinct letter inwordfrom the original total (moduloMOD). On"xyyxz"(freqs = [2, 2, 1]), that leaves20 - (3 + 3 + 1) = 13. - Does your approach still run in near-linear time if
wordcan contain arbitrary Unicode code points or integer tokens instead of 26 lowercase letters? Yes! Counting tokens inchar_countsstill takesO(n)average time, with up tod <= ndistinct tokens. Comparison-sortingsorted_freqstakesO(d log d) <= O(n log n)time (orO(n)time via bucket sort, since every frequency lies in1 .. n). Because the inner loop halts at the firstfreq < k, total inner-loop work across allkremainssum(sorted_freqs) = nmultiplications even with100,000distinct tokens. - How would you compute the binomial coefficients if the modulus
Mwere composite rather than prime? Fermat's little theorem no longer holds, and integers sharing a prime factor withMlack modular inverses. FactorMinto its prime factorsp_1, ..., p_ronce (r <= 10for 32-bitM), and factor eachi!into(unit_part[i], prime_exponents[i]), whereunit_part[i]has all factors ofp_1, ..., p_rstripped out. Becauseunit_part[i]is coprime toM(greatest common divisor1),pow(unit_part[i], -1, M)exists, andC(f, k) % Mcan be reassembled inO(r)time by multiplying unit parts withp_j^(exp[f] - exp[k] - exp[f - k]) % M.
Follow-up questions
- How would you adjust the count if a valid subsequence had to include at least two distinct letters?
- Does your approach still run in near-linear time if `word` can contain arbitrary Unicode code points or integer tokens instead of 26 lowercase letters?
- How would you compute the binomial coefficients if the modulus `M` were composite rather than prime?
Similar questions
- Final Position in Circular Passing
- Session Conversion Prediction Pipeline
- Fix State Immutability, Storage Sync, Accessibility, and URL Routing
- Scalable URL Shortening Service
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger