Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Dynamic Programming

Count Distinct Subsequences

Hard · Dynamic Programming · Asked at Google, Amazon, Microsoft

Print the number of distinct non-empty subsequences of the string, modulo 10^9 + 7.

Input

A single line with the string (lowercase letters).

Output

The count modulo 10^9 + 7.

Constraints

Let total be the number of distinct subsequences (including the empty one) so far. Appending letter c doubles them, but the ones that ended with the previous occurrence of c are counted twice: total = 2 · total − last[c], then last[c] = the total before this step. The answer is total − 1 (drop the empty one).

Example 1

Input

abc

Output

7

Example 2

Input

aba

Output

6

Example 3

Input

aaa

Output

3

Hints

  1. Each new letter can be appended to every subsequence so far — that doubles the count.
  2. But subsequences that already ended with the same letter get created twice.
  3. Subtract the count from just before that letter’s previous occurrence.

Approach

Let total = number of distinct subsequences including the empty one (start at 1). For each letter c: newTotal = 2 · total − last[c], where last[c] is the value of total just before c last appeared (0 if never). Set last[c] = total (the old value), then total = newTotal. All arithmetic is modulo 10^9 + 7, adding MOD before taking the remainder to keep it non-negative. Print total − 1 to exclude the empty subsequence.

Complexity: O(n) time · O(26) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    const long long MOD = 1000000007LL;
    string s;
    cin >> s;
    long long total = 1, last[26] = {0};
    for (char ch : s) {
        int c = ch - 'a';
        long long before = total;
        total = ((2 * total - last[c]) % MOD + MOD) % MOD;
        last[c] = before;
    }
    cout << (total - 1 + MOD) % MOD << "\n";
    return 0;
}

Python solution

MOD = 10**9 + 7
s = input().strip()
total = 1
last = [0] * 26
for ch in s:
    c = ord(ch) - 97
    before = total
    total = (2 * total - last[c]) % MOD
    last[c] = before
print((total - 1) % MOD)

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        final long MOD = 1000000007L;
        String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
        long total = 1;
        long[] last = new long[26];
        for (char ch : s.toCharArray()) {
            int c = ch - 'a';
            long before = total;
            total = ((2 * total - last[c]) % MOD + MOD) % MOD;
            last[c] = before;
        }
        System.out.println((total - 1 + MOD) % MOD);
    }
}

Solve Count Distinct Subsequences online · All practice problems