JavaScript Program to Count Distinct Subsequences
Last Updated :
11 Jun, 2024
In this article, we are going to learn about Count Distinct Subsequences in JavaScript. Counting distinct subsequences refers to determining the number of unique non-empty subarrays or subsequence combinations within a given sequence or string, without repetition of elements or order.
Example:
Input : str = "gfg"
Output : 7
The seven distinct subsequences are "", "g", "f",
"gf", "fg", "gg" and "gfg"
We will explore all the above methods along with their basic implementation with the help of examples.
Using Recursion
In this approach, we generate distinct subsequences of a given string using recursion. It stores them in a Set sn and counts them. It recursively includes and excludes each character, creating all possible subsequences and counting unique ones.
Syntax:
// Recursive Case
else {
// When a particular character is taken
op[j] = s[i];
subsequences(s, op, i + 1, j + 1);
// When a particular character isn't taken
subsequences(s, op, i + 1, j);
return;
};
Example: In this example, we generate all possible subsequences of the string "gfg" and store them in a set called sn. It then prints the size of the set, which is the count of distinct subsequences, and in this case, the output is the size of the set containing distinct subsequences of "gfg".
JavaScript
// Create an empty set to store the subsequences
let sn = new Set();
let m = 0;
// Function for generating the subsequences
function subsequences(s, op, i, j) {
// Base Case
if (i == m) {
op[j] = '\0';
// Insert each generated
// subsequence into the set
sn.add(op.join(""));
return;
}
// Recursive Case
else {
// When a particular character is taken
op[j] = s[i];
subsequences(s, op, i + 1, j + 1);
// When a particular character isn't taken
subsequences(s, op, i + 1, j);
return;
}
}
let str = "gfg";
m = str.length;
let n = Math.pow(2, m) + 1;
let op = new Array(n);
// Function Call
subsequences(str, op, 0, 0);
console.log(sn.size);
Using dynamic programming with a for...of loop
In this approach, we calculate the count of distinct subsequences for a given string s. It utilizes dynamic programming and a for...of loop to efficiently compute the count, excluding the empty subsequence, and returns the result.
Syntax:
for ( variable of iterableObjectName) {
...
}
Example: In this example, The distinctSubsequences function uses dynamic programming to count unique subsequences in the string "gfg." It returns 7 as there are seven distinct subsequences: "g," "f," "gfg," "gf," "gg," "fg," and an empty string.
JavaScript
function distinctSubsequences(s) {
const dp = new Array(s.length + 1).fill(0);
dp[0] = 1;
const lastValue = new Map();
let i = 1;
for (const char of s) {
dp[i] = 2 * dp[i - 1];
if (lastValue.has(char)) {
dp[i] -= dp[lastValue.get(char) - 1];
}
lastValue.set(char, i);
i++;
}
return dp[s.length];
}
let result = "gfg";
console.log(distinctSubsequences(result));
Bitmasking approach
In the bitmasking approach, represent each subsequence as a bitmask, where each bit corresponds to whether an element is included or not. Iterate through all possible bitmasks, counting unique ones to find distinct subsequences efficiently.
Example: In this example The function counts distinct subsequences of a string 's' using a bitmasking approach, avoiding duplicates by storing results in a set.
JavaScript
function countDistinctSubsequences(s) {
let sn = new Set();
for (let mask = 0; mask < (1 << s.length); mask++) {
let subsequence = "";
for (let i = 0; i < s.length; i++) {
if ((mask & (1 << i)) !== 0) {
subsequence += s[i];
}
}
sn.add(subsequence);
}
return sn.size;
}
let str = "gfg";
console.log(countDistinctSubsequences(str));
Using Set to Track Subsequences
Using a set to track subsequences involves recursively generating all possible subsequences of a string, storing each unique subsequence in the set, and then returning the set's size. This ensures all distinct subsequences are counted without duplicates
Example : In this example the countDistinctSubsequences function recursively generates all subsequences of a string, storing unique ones in a Set. It returns the count of distinct subsequences. The example with "abc" yields 7 distinct subsequences.
JavaScript
function countDistinctSubsequences(s) {
const set = new Set();
function helper(current, index) {
if (index === s.length) {
if (current) set.add(current);
return;
}
helper(current, index + 1);
helper(current + s[index], index + 1);
}
helper('', 0);
return set.size;
}
console.log(countDistinctSubsequences("abc"));
Similar Reads
JavaScript Count Distinct Occurrences as a Subsequence
Counting the distinct occurrences is the most common problem in string manipulation. Subsequences are the subsets of the characters in the string which appear in the same order but not necessarily in a consecutive manner. In the problem, the task is to find out the count of how many times a given su
6 min read
JavaScript Program to Print all Subsequences of a String
A subsequence is a sequence that can be derived from another sequence by deleting zero or more elements without changing the order of the remaining elements. Subsequences of a string can be found with different methods here, we are using the Recursion method, Iteration method and Bit manipulation me
3 min read
JavaScript Program to Count Strings with Consecutive 1âs
Given a number n, count the Optimized number of n-length strings with consecutive 1s in them.Examples:Input : n = 2Output : 1There are 4 strings of length 2, thestrings are 00, 01, 10 and 11. Only the string 11 has consecutive 1's.Input : n = 3Output : 3There are 8 strings of length 3, thestrings ar
7 min read
JavaScript Program to Count Distinct Elements in Every Window
In this problem we are given an array of integers and a number M. We have to find the count of distinct elements in every window of size M in the array using JavaScript. Example: Input: arr[] = [1, 2, 1, 3, 4, 2, 3], K = 4Output: 3 4 4 3Explanation: First window is [1, 2, 1, 3], count of distinct nu
4 min read
JavaScript Program Count number of Equal Pairs in a String
In this article, we are going to learn how can we count a number of equal pairs in a string. Counting equal pairs in a string involves finding and counting pairs of consecutive characters that are the same. This task can be useful in various applications, including pattern recognition and data analy
3 min read
What are Subsequences in an Array?
Subsequences are a fundamental concept in computer science and programming when working with arrays. A subsequence of an array is a sequence of elements from the array that appear in the same order, but not necessarily consecutively. In this blog post, we'll discuss subsequences, covering their defi
6 min read
Optimizing Arithmetic Progressions in Subsequences
Given a string S, a string T is considered good if following 2 conditions hold: T is a subsequence of SThe indices of the subsequence T in S forms an arithmetic progression For example, if S = "aaabb" then T = "aab" is good because T is subsequence of S at indices 1,3,5 which is an arithmetic progre
8 min read
JavaScript Program to Print All Distinct Elements in an Integer Array
Given an Array of Integers consisting of n elements with repeated elements, the task is to print all the distinct elements of the array using JavaScript. We can get the distinct elements by creating a set from the integer array. Examples: Input : arr = [ 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9, 9 ] Outpu
3 min read
Increase the count of given subsequences by optimizing the Array
Given an array X[] of length N. Which contains the alternate frequency of 0s and 1s in Binary String starting from 0. Then the task is to maximize the count of the "01" subsequence where you can choose two different elements of X[], let's say Xi and Xj such that abs (i - j) = 2, and then swap Xi and
11 min read
String Subsequence and Substring in Python
Subsequence and Substring both are parts of the given String with some differences between them. Both of them are made using the characters in the given String only. The difference between them is that the Substring is the contiguous part of the string and the Subsequence is the non-contiguous part
5 min read