Program to find number of distinct subsequences in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s, we have to count the number of distinct subsequences of the string s. If the answer is too large then return result modulo 10^9 + 7.

So, if the input is like s = "bab", then the output will be 6 because there are 6 different sequences, these are "a", "b, "ba", "ab", "bb", "abb".

To solve this, we will follow these steps −

  • dp := an array whose size is same of s and filled with 0

  • m := 10^9 + 7

  • for each index i and item char in s, do

    • ind := index of i-th char in s from right

    • dp[i] := 1 + (sum of all elements in dp[from index 0 to i-1]) mod m if ind is same as -1 otherwise (sum of all elements in dp[from index ind to i-1]) mod m

  • return sum of all elements in dp mod m


Let us see the following implementation to get better understanding

def solve(s):
   dp, m = [0] * len(s), 10**9 + 7
   for i, char in enumerate(s):
      ind = s.rfind(char, 0, i)
      dp[i] = 1 + sum(dp[:i]) % m if ind == -1 else sum(dp[ind:i]) % m
   return sum(dp) % m

s = "bab"


"abcd", "abcdbcd"


Updated on 07-Oct-2021 08:45:11