- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to find number of distinct subsequences in Python

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

## Example

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" print(solve(s))

## Input

"abcd", "abcdbcd"

## Output

6

- Related Questions & Answers
- Program to find number of different subsequences GCDs in Python
- Program to find number of increasing subsequences of size k in Python
- Distinct Subsequences in C++
- Program to find number of arithmetic subsequences from a list of numbers in Python?
- Distinct Subsequences II in C++
- Distinct Subsequences in C++ Programming
- Program to find number of subsequences that satisfy the given sum condition using Python
- Program to find number of unique subsequences same as target in C++
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Program to find number of distinct quadruple that forms target sum in python
- Program to find number of subsequences with i, j and k number of x, y, z letters in Python
- Program to find number of distinct combinations that sum up to k in python
- Program to find out number of distinct substrings in a given string in python
- Program to find maximize palindrome length from subsequences in Python
- Program to find number of distinct island shapes from a given matrix in Python