Count of unique Subsequences of given String with lengths in range [0, N]
Last Updated :
23 Jul, 2025
Given a string S of length N, the task is to find the number of unique subsequences of the string for each length from 0 to N.
Note: The uppercase letters and lowercase letters are considered different and the result may be large so print it modulo 1000000007.
Examples:
Input: S = "ababd"
Output:
Number of unique subsequences of length 0 is 1
Number of unique subsequences of length 1 is 3
Number of unique subsequences of length 2 is 6
Number of unique subsequences of length 3 is 8
Number of unique subsequences of length 4 is 5
Number of unique subsequences of length 5 is 1
Explanation: 0 length subsequences are 1-> {}
1 length subsequences are 3 -> a, b, d
2 length subsequences are 6 -> ab, aa, ad, ba, bd, bb
3 length subsequences are 8 -> aab, aad, abb, abd, bab, aba, bbd, bad
4 length subsequences are 5 -> aabd, abab, abad, babd, abbd
5 length subsequences are 1 -> ababd
Input: GeeksForGeeks
Output:
Number of unique subsequences of length 0 is 1
Number of unique subsequences of length 1 is 7
Number of unique subsequences of length 2 is 43
Number of unique subsequences of length 3 is 163
Number of unique subsequences of length 4 is 402
Number of unique subsequences of length 5 is 703
Number of unique subsequences of length 6 is 917
Number of unique subsequences of length 7 is 918
Number of unique subsequences of length 8 is 711
Number of unique subsequences of length 9 is 421
Number of unique subsequences of length 10 is 185
Number of unique subsequences of length 11 is 57
Number of unique subsequences of length 12 is 11
Number of unique subsequences of length 13 is 1
Naive Approach: The basic approach to solve the problem is as follows:
Generate every possible subsequence and store it in a set to get unique results. Then traverse each of the subsequence from that set and count it on the basis of their lengths.
Follow the steps to solve the problem:
- Use recursion to generate each subsequence and store it in a set to get unique occurrences.
- Use a map to store the count of subsequences for each possible length.
- Traverse each subsequence, find the length of the subsequence and update the count of the appropriate group of subsequences.
- Traverse map and print both its keys (length of subsequence) & value (count of subsequence).
Below is the implementation for the above approach:
C++14
// C++ code to implement the above approach.
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000000007
typedef long long ll;
unordered_set<string> sn;
// Function to find subsequences
void subsequences(char s[], char op[],
ll i, ll j)
{
if (s[i] == '\0') {
op[j] = '\0';
sn.insert(op);
return;
}
else {
op[j] = s[i];
subsequences(s, op, i + 1, j + 1);
subsequences(s, op, i + 1, j);
return;
}
}
map<ll, ll> getCount()
{
map<ll, ll> freq;
for (auto x : sn) {
freq[x.length()]
= (freq[x.length()] + 1) % MAX;
}
return freq;
}
// Function to print the answer
void printSubsequences(string& S)
{
ll m = S.length();
char op[m + 1];
subsequences(&S[0], &op[0], 0, 0);
map<ll, ll> ans = getCount();
for (auto& x : ans)
cout << "Number of unique subsequences of length "
<< x.first << " is " << x.second << endl;
}
// Driver Code
int main()
{
string S = "ababd";
// Function call
printSubsequences(S);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
import java.util.*;
class GFG {
static int MAX = 1000000007;
static HashSet<String> sn;
// Function to find subsequences
static void subsequences(String s, String op, int i)
{
if (i == s.length()) {
sn.add(new String(op));
return;
}
else {
subsequences(s, op + s.charAt(i), i + 1);
subsequences(s, op, i + 1);
return;
}
}
static HashMap<Long, Long> getCount()
{
HashMap<Long, Long> freq = new HashMap<>();
for (String x : sn) {
long len = x.length();
freq.put(len, (freq.getOrDefault(len, 0L) + 1)
% MAX);
}
return freq;
}
// Function to print the answer
static void printSubsequences(String S)
{
int m = S.length();
String op = "";
sn = new HashSet<>();
subsequences(S, op, 0);
HashMap<Long, Long> ans = getCount();
for (Long x : ans.keySet())
System.out.println(
"Number of unique subsequences of length "
+ x + " is " + ans.get(x));
}
public static void main(String[] args)
{
String S = "ababd";
// Function call
printSubsequences(S);
}
}
// This code is contributed by Karandeep1234
Python3
# Python3 code to implement the above approach.
MAX = 1000000007
sn = set()
# Function to find subsequences
def subsequences(s, op, i):
global sn
if (i == len(s)):
sn.add("".join(op))
else:
subsequences(s, op + s[i], i + 1)
subsequences(s, op, i + 1)
# Function to find count of subsequences
# with a particular length
def getCount():
freq = dict()
for x in sn:
if len(x) in freq:
freq[len(x)] = (freq[len(x)] + 1) % MAX
else:
freq[len(x)] = 1 % MAX
return freq
# Function to print the answer
def printSubsequences(s):
global op
m = len(s)
op = ""
subsequences(s, op, 0)
ans = getCount()
for x in sorted(ans):
print("Number of unique subsequences of length", x, "is", ans[x])
# Driver Code
s = "ababd"
# Function call
printSubsequences(s)
# This code is contributed by phasing17
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
class GFG {
static int MAX = 1000000007;
static HashSet<string> sn;
// Function to find subsequences
static void subsequences(string s, string op, int i)
{
if (i == s.Length) {
sn.Add(new string(op));
return;
}
else {
subsequences(s, op + s[i], i + 1);
subsequences(s, op, i + 1);
return;
}
}
// Function to build the dictionary of counts
static Dictionary<long, long> getCount()
{
Dictionary<long, long> freq
= new Dictionary<long, long>();
foreach(string x in sn)
{
long len = x.Length;
if (freq.ContainsKey(len))
freq[len] = (freq[len] + 1) % MAX;
else
freq[len] = 1L;
}
return freq;
}
// Function to print the answer
static void printSubsequences(string S)
{
int m = S.Length;
string op = "";
sn = new HashSet<string>();
subsequences(S, op, 0);
Dictionary<long, long> ans = getCount();
List<long> keyList = new List<long>(ans.Keys);
keyList.Sort();
foreach(var key in keyList) Console.WriteLine(
"Number of unique subsequences of length " + key
+ " is " + ans[key]);
}
// Driver code
public static void Main(string[] args)
{
string S = "ababd";
// Function call
printSubsequences(S);
}
}
// This code is contributed by phasing17
JavaScript
// JavaScript code to implement the above approach.
let MAX = 1000000007;
let sn = new Set();
// Function to find subsequences
function subsequences(s, op, i)
{
if (i == s.length)
sn.add(op);
else
{
subsequences(s, op + s[i], i + 1);
subsequences(s, op, i + 1);
}
}
// Function to find count of subsequences
// with a particular length
function getCount()
{
let freq = {};
for (let x of sn)
{
if (freq.hasOwnProperty(x.length))
freq[x.length] = (freq[x.length] + 1) % MAX;
else
freq[x.length] = 1 % MAX;
}
return freq;
}
// Function to print the answer
function printSubsequences(s)
{
let m = s.length;
let op = "";
subsequences(s, op, 0);
let ans = getCount();
let keys = Object.keys(ans);
keys.sort();
for (let x of keys)
console.log("Number of unique subsequences of length", x, "is", ans[x]);
}
// Driver Code
let s = "ababd";
// Function call
printSubsequences(s);
// This code is contributed by phasing17
OutputNumber of unique subsequences of length 0 is 1
Number of unique subsequences of length 1 is 3
Number of unique subsequences of length 2 is 6
Number of unique subsequences of length 3 is 8
Number of unique subsequences of length 4 is 5
Number of unique subsequences of length 5 is 1
Time Complexity: O(2N)
Auxiliary Space: O(N)
Efficient Approach: The idea to solve the problem using dynamic programming is based on the following observations:
Observations:
Consider a character at ith position to be the end character of the subsequence with length j.
Let the total possible ways be denoted as f(i, j).
This value depends on the values of f(i-1, j) and f(i-1, j-1), i.e. it is the summation of f(i-1, j) and f(i-1, j-1).
So f(i, j) = f(i-1, j) + f(i-1, j-1)
But if the ith character has occurred earlier in an index k, then in the above case, value of f(k-1, j-1) is being considered twice:
- once for f(k, j) and
- next for f(i, j) [as f(k-1, j-1) is a part of f(i-1, j-1) and f(k, j) is part of f(i-1, j)]
and both the time the resulting subsequences are same because the kth and ith character are same.
So, in that case, we need to consider the value only once. Therefore f(i, j) = f(i-1, j) + f(i-1, j-1) - f(k-1, j-1)
So there are two cases:
- f(i, j) = f(i-1, j) + f(i-1, j-1) when ith character does not occur earlier
- f(i, j) = f(i-1, j) + f(i-1, j-1) - f(k-1, j-1) when ith character occurs earlier at kth index.
Follow the below steps to solve the problem:
- Create a 2-dimensional array dp[][] where dp[i][j] represents the number of unique subsequences of S until i-th element in string and subsequences are of length j.
- Create an array (say last[]) to store the previous occurrence of a character.
- Use the transition function shown above to calculate the value of dp[i][j].
- Base cases are dp[0][0]=1 and dp[i][j]=0 for every j>i.
Below is the implementation of the above approach:
C++14
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mod 1000000007
// Function to find subsequences
void findSubsequences(string& s)
{
int n = s.length();
ll dp[n + 2][n + 2];
memset(dp, 0, sizeof(dp));
vector<ll> last(256, -1);
dp[0][0] = 1;
for (int i = 0; i < n + 1; i++) {
for (int j = i + 1; j < n + 1; j++)
dp[i][j] = 0;
}
// Loop to implement the dp transition
for (int i = 1; i <= n; i++) {
for (int j = 0; j < n + 1; j++) {
dp[i][j] = (dp[i][j]
+ dp[i - 1][j])
% mod;
if (j >= 1) {
dp[i][j]
= (dp[i][j]
+ dp[i - 1][j - 1])
% mod;
if (last[s[i - 1]] != -1) {
dp[i][j]
= (dp[i][j]
- dp[last[s[i - 1]]][j - 1])
% mod;
}
}
}
last[s[i - 1]] = (i - 1) % mod;
}
cout << "Number of unique subsequences of length 0 is 1"
<< endl;
for (int i = 1; i <= n; i++)
cout << "Number of unique subsequences of length "
<< i << " is " << dp[n][i] << endl;
}
// Driver code
int main()
{
string S = "ababd";
// Function call
findSubsequences(S);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG
{
static int mod = 1000000007;
// Function to find subsequences
static void findSubsequences(String s)
{
int n = s.length();
int[][] dp = new int[n + 2][n + 2];
for (int i = 0; i < n + 2; i++) {
for (int j = 0; j < n + 2; j++)
dp[i][j] = 0;
}
int[] last = new int[256];
for (int i = 0; i < 256; i++) {
last[i] = -1;
}
dp[0][0] = 1;
for (int i = 0; i < n + 1; i++) {
for (int j = i + 1; j < n + 1; j++)
dp[i][j] = 0;
}
// Loop to implement the dp transition
for (int i = 1; i <= n; i++) {
for (int j = 0; j < n + 1; j++) {
dp[i][j] = (dp[i][j]
+ dp[i - 1][j])
% mod;
if (j >= 1) {
dp[i][j]
= (dp[i][j]
+ dp[i - 1][j - 1])
% mod;
if (last[s.charAt(i - 1)] != -1) {
dp[i][j]
= (dp[i][j]
- dp[last[s.charAt(i - 1)]][j - 1])
% mod;
}
}
}
last[s.charAt(i - 1)] = (i - 1) % mod;
}
System.out.println( "Number of unique subsequences of length 0 is 1");
for (int i = 1; i <= n; i++)
System.out.println("Number of unique subsequences of length "
+ i + " is " + dp[n][i]);
}
// Driver Code
public static void main(String args[])
{
String S = "ababd";
// Function call
findSubsequences(S);
}
}
// This code is contributed by sanjoy_62.
Python3
## Python program for the above approach:
mod = 1000000007
## Function to find subsequences
def findSubsequences(s):
n = len(s);
dp = [];
for i in range(0, n+2):
dp.append([0]*(n+2))
last = [-1]*256
dp[0][0] = 1;
## Loop to implement the dp transition
for i in range(1, n+1):
for j in range(0, n+1):
dp[i][j] = (dp[i][j] + dp[i - 1][j]) % mod;
if (j >= 1):
dp[i][j] = (dp[i][j] + dp[i - 1][j - 1]) % mod;
if (last[ord(s[i - 1])] != -1):
dp[i][j] = (dp[i][j] - dp[last[ord(s[i - 1])]][j - 1]) % mod
last[ord(s[i - 1])] = (i - 1) % mod
print("Number of unique subsequences of length 0 is 1")
for i in range(1, n+1):
print("Number of unique subsequences of length", i, "is", dp[n][i])
## Driver code
if __name__=='__main__':
S = "ababd";
## Function call
findSubsequences(S)
# This code is contributed by subhamgoyal2014.
C#
// C# program for the above approach
using System;
class GFG
{
static int mod = 1000000007;
// Function to find subsequences
static void findSubsequences(String s)
{
int n = s.Length;
int[,] dp = new int[n + 2, n + 2];
for (int i = 0; i < n + 2; i++)
{
for (int j = 0; j < n + 2; j++)
dp[i, j] = 0;
}
int[] last = new int[256];
for (int i = 0; i < 256; i++)
{
last[i] = -1;
}
dp[0, 0] = 1;
for (int i = 0; i < n + 1; i++)
{
for (int j = i + 1; j < n + 1; j++)
dp[i, j] = 0;
}
// Loop to implement the dp transition
for (int i = 1; i <= n; i++)
{
for (int j = 0; j < n + 1; j++)
{
dp[i, j] = (dp[i, j]
+ dp[i - 1, j])
% mod;
if (j >= 1)
{
dp[i, j]
= (dp[i, j]
+ dp[i - 1, j - 1])
% mod;
if (last[s[i - 1]] != -1)
{
dp[i, j]
= (dp[i, j]
- dp[last[s[i - 1]], j - 1])
% mod;
}
}
}
last[s[i - 1]] = (i - 1) % mod;
}
Console.WriteLine("Number of unique subsequences of length 0 is 1");
for (int i = 1; i <= n; i++)
Console.WriteLine("Number of unique subsequences of length "
+ i + " is " + dp[n, i]);
}
// Driver Code
public static void Main()
{
String S = "ababd";
// Function call
findSubsequences(S);
}
}
// This code is contributed by saurabh_jaiswal.
JavaScript
// JavaScript program for the above approach
const mod = 1000000007;
// Function to find subsequences
function findSubsequences(s)
{
var n = s.length;
s = s.split("");
// mapping the string s to an array
// corresponding to the ascii code
// of each letter in s
for (var i = 0; i < n; i++)
s[i] = s[i].charCodeAt(0);
var dp = [];
for (var i = 0; i < n + 2; i++)
dp.push(new Array(n + 2));
for (var i = 0; i < n + 2; i++) {
for (var j = 0; j < n + 2; j++)
dp[i][j] = 0;
}
var last = new Array(256).fill(-1);
dp[0][0] = 1;
for (var i = 0; i < n + 1; i++) {
for (var j = i + 1; j < n + 1; j++)
dp[i][j] = 0;
}
// Loop to implement the dp transition
for (var i = 1; i <= n; i++) {
for (var j = 0; j < n + 1; j++) {
dp[i][j] = (dp[i][j]
+ dp[i - 1][j])
% mod;
if (j >= 1) {
dp[i][j]
= (dp[i][j]
+ dp[i - 1][j - 1])
% mod;
if (last[s[i - 1]] != -1) {
dp[i][j]
= (dp[i][j]
- dp[last[s[i - 1]]][j - 1])
% mod;
}
}
}
last[s[i - 1]] = (i - 1) % mod;
}
console.log( "Number of unique subsequences of length 0 is 1");
for (var i = 1; i <= n; i++)
console.log("Number of unique subsequences of length "
+ i + " is " + dp[n][i]);
}
// Driver Code
var S = "ababd";
// Function call
findSubsequences(S);
// This code is contributed by phasing17
OutputNumber of unique subsequences of length 0 is 1
Number of unique subsequences of length 1 is 3
Number of unique subsequences of length 2 is 6
Number of unique subsequences of length 3 is 8
Number of unique subsequences of length 4 is 5
Number of unique subsequences of length 5 is 1
Time Complexity: O(N2)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem