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_000
  • word consists 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

  1. 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 word of length n up to 100,000, we want the number of balanced subsequences modulo 1_000_000_007.

  2. Why listing every subsequence is too slow

    At each of the n indices, we either include or skip that position. That gives 2^n - 1 non-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 += 1
    

    For n = 10 (2^10 - 1 = 1,023), this brute-force check finishes instantly and serves as our test oracle. For n = 100,000, 2^100,000 exceeds 30,000 decimal digits, so we must count valid index subsets combinatorially rather than enumerating them.

  3. 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 in word). Because each non-empty balanced subsequence has a unique shared count k, partitioning by k splits 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 k is 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 preserves word's order!

    Suppose a letter occurs freq times in word. When building a bucket-k subsequence, 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 appears 0 or k times. Exactly one of those combinations omits every single letter (the empty subsequence). Subtracting 1 leaves the exact count for bucket k:

    ways(k) = ( product over all distinct letters of (1 + C(freq, k)) ) - 1
    

    Notice that character order in word drops out completely — only each letter's total count freq matters!

  4. 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 number inv satisfying (x * inv) % MOD == 1.

    Because MOD = 1_000_000_007 is prime and n <= 100,000 < MOD, none of 1!, 2!, ..., n! is a multiple of MOD. By Fermat's little theorem, x^(MOD - 2) % MOD equals the modular inverse of x.

    Even better, instead of calling pow() n times, we invert n! once via pow(fact[n], MOD - 2, MOD) and step down from n to 1 using 1 / (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) % MOD
    

    After this O(n) setup, every choose(freq, k) lookup runs in O(1) time.

  5. Keep the loop over k linear by sorting frequencies

    Whenever a letter has freq < k, it cannot contribute k copies, so its factor is 1 + 0 = 1. Multiplying a product by 1 leaves it unchanged.

    Sorting sorted_freqs in descending order lets us break out of the inner loop at the very first letter with freq < 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 freq is visited only for k = 1, 2, ..., freq. Across all outer iterations, the inner loop performs sum(sorted_freqs) = n multiplications in total — linear in len(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) % MOD
    

    Note on (ways_for_k - 1) % MOD: if ways_for_k wraps around to 0 modulo MOD, ways_for_k - 1 is -1. Python's % MOD maps -1 to MOD - 1 (0 .. MOD - 1), whereas in C++ or Java you would write (ways_for_k - 1 + MOD) % MOD.

  6. 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 = 20
    

    For Example 2 (word = "cat"), sorted_freqs = [1, 1, 1], so only k = 1 runs: 2 * 2 * 2 - 1 = 7.

  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 to O(n) for lowercase letters. Counting characters and building the fact and inv_fact tables each scan n elements once (O(n)), with a single pow(..., MOD - 2, MOD) call taking O(log MOD) (~30) multiplications. Sorting the d character counts takes O(d log d). Finally, because frequencies are sorted descending and the inner loop breaks as soon as freq < k, each letter with frequency freq is visited freq times across all k, so the nested loop performs sum(freq) = n multiplications plus at most n break checks overall.
  • Space: O(n). We store two arrays (fact and inv_fact) of length n + 1, plus a frequency dictionary of at most d <= 26 entries.

Edge cases

  • Single character ("a"): Only k = 1 runs, giving (1 + 1) - 1 = 1.
  • One letter repeated n times ("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 only k = 1 runs 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) = 2 counts both automatically.
  • Huge intermediate counts (n = 100,000): True counts can exceed 2^100,000, so reducing % MOD after 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 index 0 and index 3, so string deduplication undercounts valid index subsets.
  • Subtracting 1 only once at the very end instead of once per k: Every k iteration includes its own "all letters stay out" empty option in ways_for_k, so 1 must be subtracted for each k.
  • Calling math.comb(freq, k) inside the loop: At n = 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 under 10^9 + 7.
  • Breaking on freq < k without sorting frequencies descending first: On "abbccc" with unsorted counts [1, 2, 3], breaking when 1 < 2 skips 'b' and 'c' for k = 2 and k = 3, returning 23 instead of 31.
  • Negative modulo in C++ or Java: When ways_for_k equals 0 modulo MOD, ways_for_k - 1 is -1. Python's % MOD wraps -1 to MOD - 1, whereas C++ and Java preserve -1 unless you write (ways_for_k - 1 + MOD) % MOD.

Alternative approaches

  • Scan all 26 letters per k without sorting or breaking: With at most 26 lowercase letters, checking every present letter for each k = 1 .. max_freq performs at most 26 * n steps (~2.6 * 10^6 operations), which also passes for d <= 26 — though sorting + breaking is cleaner and stays O(n) even on unbounded alphabets.
  • Pascal's triangle table for C(f, k): Computing C(f, k) = (C(f - 1, k - 1) + C(f - 1, k)) % MOD avoids modular inverses for small n (n <= 2,000), but takes O(n^2) time and memory (~10^10 cells at n = 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 - 1 index 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 in word from the original total (modulo MOD). On "xyyxz" (freqs = [2, 2, 1]), that leaves 20 - (3 + 3 + 1) = 13.
  • 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? Yes! Counting tokens in char_counts still takes O(n) average time, with up to d <= n distinct tokens. Comparison-sorting sorted_freqs takes O(d log d) <= O(n log n) time (or O(n) time via bucket sort, since every frequency lies in 1 .. n). Because the inner loop halts at the first freq < k, total inner-loop work across all k remains sum(sorted_freqs) = n multiplications even with 100,000 distinct tokens.
  • How would you compute the binomial coefficients if the modulus M were composite rather than prime? Fermat's little theorem no longer holds, and integers sharing a prime factor with M lack modular inverses. Factor M into its prime factors p_1, ..., p_r once (r <= 10 for 32-bit M), and factor each i! into (unit_part[i], prime_exponents[i]), where unit_part[i] has all factors of p_1, ..., p_r stripped out. Because unit_part[i] is coprime to M (greatest common divisor 1), pow(unit_part[i], -1, M) exists, and C(f, k) % M can be reassembled in O(r) time by multiplying unit parts with p_j^(exp[f] - exp[k] - exp[f - k]) % M.

Follow-up questions

Similar questions

More HackerRank interview questions

All 5 HackerRank questions →