Patterns/Part VIII - Cross-Topic Deep Dives/Subsequence Counting

Pattern Reference

Subsequence Counting

"Count distinct subsequences, number of subsequences with given sum/product, subsequence pattern matching."

Loading...

Deep Dive Tutorial

Subsequence counting DP: at each element, we either skip it or include it. For counting subsequences matching string t in string s: dp[i][j] = count of ways to form t[0..j-1] from s[0..i-1]. For counting subsequences with sum k: dp[i][j] = ways to pick a subsequence from first i elements with sum j. Track total with modular arithmetic when counts are large.

Subsequence counting patterns
// Count distinct subsequences of s equal to t
function countSubseq(s, t) {
    const m = s.length, n = t.length;
    const dp = Array.from({length: m + 1}, () => new Array(n + 1).fill(0));
    for (let i = 0; i <= m; i++) dp[i][0] = 1;
    for (let i = 1; i <= m; i++)
        for (let j = 1; j <= n; j++) {
            dp[i][j] = dp[i-1][j]; // skip s[i-1]
            if (s[i-1] === t[j-1]) dp[i][j] += dp[i-1][j-1]; // include
        }
    return dp[m][n];
}

// Count subsequences with sum exactly k
function countSubseqSum(arr, k, MOD = 1e9 + 7) {
    const dp = new Array(k + 1).fill(0); dp[0] = 1;
    for (const x of arr) {
        for (let j = k; j >= x; j--)
            dp[j] = (dp[j] + dp[j - x]) % MOD;
    }
    return dp[k];
}

// Count non-empty subsequences with min+max ≤ target
// Sort first, then for each right endpoint r, find leftmost l where arr[l]+arr[r] ≤ target
// Count = 2^(r-l) (any subset of elements between l and r)
function countSubseqMinMax(nums, target) {
    const MOD = 1e9 + 7;
    nums.sort((a, b) => a - b);
    const n = nums.length;
    const pow2 = new Array(n).fill(1n);
    for (let i = 1; i < n; i++) pow2[i] = pow2[i-1] * 2n % BigInt(MOD);
    let ans = 0n, l = 0;
    for (let r = 0; r < n; r++) {
        while (nums[l] + nums[r] > target) l++;
        ans = (ans + pow2[r - l]) % BigInt(MOD);
    }
    return Number(ans);
}

Worked Problems

hash
Subsequence counting patterns:
- Count equal to t: dp[i][j] = ways to form t[0..j-1] from s[0..i-1]
- Count with sum k: 0/1 knapsack variant, O(n × k)
- Count with min+max ≤ target: sort + two pointers + 2^(r-l)
- Count non-decreasing: stars and bars or DP by last element

Modular arithmetic tip: When using 2^k mod p, precompute powers[0..n] for O(1) lookup.

Key identity: 2^(r-l) counts all non-empty subsets of elements from index l to r (when sorted, these give all valid (min, max) pairs).