Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Program to Count Distinct Subsequences
Next article icon

JavaScript Program to Count Distinct Subsequences

Last Updated : 11 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Table of Content

  • Using Recursion
  • Using dynamic programming with a for...of loop
  • Bitmasking approach
  • Using Set to Track Subsequences

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); 

Output
7 

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));  

Output
7 

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)); 

Output
7 

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"));  

Output
7 

Next Article
JavaScript Program to Count Distinct Subsequences

K

kohliami558i
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Program
  • Geeks Premier League 2023

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 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
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences