KatInterview

Count Subsequences With Uniform Letter Frequency

Math & Bit ManipulationAuto-graded · 22 test cases
MediumAuto-gradedMath & Bit Manipulationcombinatoricsmodular arithmeticfrequency counting

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