how to find the number of distinct subsequences of a string?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Finding the number of distinct subsequences of a string is a fascinating problem with applications in bioinformatics, text processing, and more. In this article, we'll delve into the concept, a dynamic programming approach to solve it efficiently, and demonstrate the solution with examples.
Understanding Subsequences
A subsequence is a sequence derived from another sequence by removing some elements (can be none) without changing the order of the remaining elements. For example, the string "abc" has the subsequences: "", "a", "b", "c", "ab", "ac", "bc", "abc".
Problem Definition
Given a string `S`, find the number of distinct subsequences it can generate.
Solution Approach
Dynamic Programming
A dynamic programming approach leverages breaking down the problem into smaller, manageable subproblems. We use a one-dimensional array `dp` where `dp[i]` represents the number of distinct subsequences that can be formed using the first `i` characters of `S`.
Algorithm
- Initialize DP Array: • Create a DP array of size `n+1` (where `n` is the length of the string `S`) initialized to zero. Set `dp[0] = 1` because the empty subsequence is always a valid subsequence.
- Keep Track of the Last Occurrence: • Maintain a dictionary `last_occurrence` to store the last occurrence index of each character.
- DP Transition: • For each character `S[i]` (1-indexed for simplicity), calculate the number of subsequences:
• If the character `S[i]` has appeared before at `last_occurrence[S[i]] = j`: • Finally, update `last_occurrence[S[i]] = i`.
- Return the Result: • `dp[n]` holds the number of distinct subsequences.
Example
Consider the string `S = "abc"`:
• Initialize: `dp = [1, 0, 0, 0]` and `last_occurrence` as an empty dictionary. • Iterating over `S`: • For `i = 1` (character 'a'): • `dp[1] = 2 * dp[0] = 2 * 1 = 2` • Update `last_occurrence = {'a': 1}` • For `i = 2` (character 'b'): • `dp[2] = 2 * dp[1] = 2 * 2 = 4` • Update `last_occurrence = {'a': 1, 'b': 2}` • For `i = 3` (character 'c'): • `dp[3] = 2 * dp[2] = 2 * 4 = 8` • Update `last_occurrence = {'a': 1, 'b': 2, 'c': 3}`
Finally, `dp[3] = 8` indicates there are 8 distinct subsequences of "abc".
Complexity Analysis
• Time Complexity: , where `n` is the length of string `S`. This is due to the single pass over `S` and constant-time operations on the `last_occurrence` dictionary. • Space Complexity: due to the `dp` array and space for managing `last_occurrence`.
Key Points
Here is a table summarizing key steps:
| Step | Explanation |
Initialize dp | dp\[0] = 1 since empty subsequence exists for any string. |
| Traverse Character | Iteratively compute dp\[i] from dp\[i-1] twice. |
| Handle Repetitions | If S\[i] repeated, subtract repeated subsequences count. |
| Result | dp\[n] gives the number of distinct subsequences. |
Conclusion
Finding the number of distinct subsequences in a string is effectively solved using a dynamic programming approach, leveraging memoization and careful handling of repeated characters. This problem highlights the power of using a systematic method to address the combinatorial explosion in subsequence calculations.
Related reading
- How to find the only number in an array that doesn't occur twice
- How to find the smallest number with just 0 and 1 which is divided by a given number?
- How to find the sum of an array of numbers
- How to find the total number of Increasing sub-sequences of certain length with Binary Index TreeBIT
- How to find the winner of a tic-tac-toe game of any size?
- How to find two most distant points?
- How to find what is the rank of each element in an integer array
- How to find whether the shortest path from s any starting vertex to v any vertex in the undirected graph is unique or not?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.