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 Count Distinct Occurrences as a Subsequence
Next article icon

JavaScript Count Distinct Occurrences as a Subsequence

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

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 subsequence appears as a distinct occurrence in the given larger string. In this article, we will explore various approaches to count distinct occurrences as a subsequence

There are different approaches to counting distinct occurrences as a subsequence in JavaScript. Let’s discuss each one of them.

Table of Content

  • Using Recursion with Memoization
  • Using String Iteration
  • Using BackTracking
  • Dynamic Programming with Space Optimization


Using Recursion with Memoization

  • In this approach, we have defined the recursive function which finds the two possibilities at each step: whether the current characters in the string match or not.
  • The memoization table is used to store the previously computed output results for the specific indices, and it ensures that there are no repeat calculations.
  • Using this approach, we can traverse all possible combinations of characters and return the count of distinct occurrences of subsequences.

Example: In this example, we will count distinct occurrences as a subsequence using Recursion with Memoization approach

JavaScript
function countSeq(str, seq) {     const memoTable = new Map();     function helperFunction(strIdx, seqIdx) {         if (seqIdx === seq.length) return 1;         if (strIdx === str.length) return 0;         const key = strIdx + ',' + seqIdx;         if (memoTable.has(key)) return memoTable.get(key);         let count = 0;         if (str[strIdx] === seq[seqIdx]) {             count += helperFunction(strIdx + 1, seqIdx + 1);         }         count += helperFunction(strIdx + 1, seqIdx);         memoTable.set(key, count);         return count;     }     return helperFunction(0, 0); }  const str = "geeksforgeeks"; const seq = "ge"; console.log(countSeq(str, seq)); 

Output
6 

Time complexity: O(2 ^ N), where 'N' is the length of the input.

Auxiliary space: O(2 ^ N), The space complexity is determined by the space used for the memoTable, which is a Map data structure. Stores for all unique combinations of strIndex and subseqIndex.

Using String Iteration

  • In this approach, we are creating a 2D array('dp') to store the counts of each step in which 'dp[i][j]' represents the count of each distinct subsequence of 'subseqInput' in the 1st 'i' characters of 'stringInput'.
  • This approach iterates over both the input strings, comparing the characters and when the match is found.
  • It adds the count from the previous characters with and without including the current character, this ensures that all possible distinct subsequences are computed.

Example: In this example, we will count distinct occurrences as a subsequence using the String Iteration approach.

JavaScript
function countSeq(str, seq) {     const m = str.length;     const n = seq.length;     const dp = Array(m + 1).fill(0).map(() => Array(n + 1).fill(0));     for (let i = 0; i <= m; i++) {         dp[i][0] = 1;     }     for (let i = 1; i <= m; i++) {         for (let j = 1; j <= n; j++) {             if (str[i - 1] === seq[j - 1]) {                 dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];             } else {                 dp[i][j] = dp[i - 1][j];             }         }     }      return dp[m][n]; } const str = "geeksforgeeks"; const pattern = "ge"; console.log(countSeq(str, pattern)); 

Output
6 

Time Complexity: O(M * N), where 'M' is the length of the strInput, and 'N' is the length of the subseqInput.

Auxiliary space: O(M * N), a two-dimensional array that stores the results of subproblems during dynamic programming.

Using BackTracking

  • In this BackTracking Apporach, we are using the recursive backtracking algo that actually counts the nu,ber of distinct subsequence of the input 'subseqInput' in 'strInput'.
  • Here, the algo iterates over all the possible cobinations off the characters in the 'strInput' to constrcut the subsequence that matches the 'subseqInput'.
  • In the every step, either the current character from the 'strInput' is included in the subsequence that is formed or it is skiped.
  • This recursion contniues till there is proper constrcution of subsequences that matches subseqInput, in that case we increment the count value or we reach to the end of the string.

Example: In this example, we will count distinct occurrences as a subsequence using the BackTracking approach.

JavaScript
function fun(str, subSeq) {     function countSeq(strIndex, subseqIndex) {         if (subseqIndex === subSeq.length) {             count++;             return;         }         if (strIndex === str.length) {             return;         }         if (str[strIndex] === subSeq[subseqIndex]) {             countSeq(strIndex + 1, subseqIndex + 1);         }         countSeq(strIndex + 1, subseqIndex);     }     let count = 0;     countSeq(0, 0);     return count; }  const str = "geeksforgeeks"; const pattern = "ge"; console.log(fun(str, pattern)); 

Output
6 

Time Complexity: O(2^N), where 'N' is the lenthgo of 'strInput'.

Auxiliary space: O(N), where 'N' is the lenthgo of 'strInput'., due to the maximum depth of the recursive call stack, addition to constant space for varibaes and function call oerhead.

Dynamic Programming with Space Optimization

In this approach, instead of using a 2D array to store the counts of subsequences, we use a 1D array (or two 1D arrays) to keep track of the counts. This reduces the space complexity significantly while maintaining the time complexity.

The main idea is to use two arrays, current and previous, where current[j] represents the count of subsequences of subSeq in the first i characters of str and previous[j] represents the count for the previous row in the dynamic programming table.

Example:

JavaScript
function countSeqOptimized(str, seq) {     const m = str.length;     const n = seq.length;     if (n > m) return 0; // If subseq length is greater than string length, return 0          let previous = Array(n + 1).fill(0);     let current = Array(n + 1).fill(0);     previous[0] = 1; // Base case: an empty subsequence is a subsequence of any string      for (let i = 1; i <= m; i++) {         current[0] = 1; // Base case: an empty subsequence is a subsequence of any string         for (let j = 1; j <= n; j++) {             if (str[i - 1] === seq[j - 1]) {                 current[j] = previous[j - 1] + previous[j];             } else {                 current[j] = previous[j];             }         }         // Swap current and previous arrays         [previous, current] = [current, previous];     }      return previous[n]; }  const str = "geeksforgeeks"; const seq = "ge"; console.log(countSeqOptimized(str, seq)); 

Output
6 

Time Complexity: O(MxN) O (M×N), where ? M is the length of str and ? N is the length of seq.

Auxiliary Space: O(N) O (N), because we are using two 1D arrays of size N+1.


Next Article
JavaScript Count Distinct Occurrences as a Subsequence

G

gpancomputer
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Program

Similar Reads

    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
    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
    Count subarrays having at least X distinct elements that occur exactly Y times
    Given three integers N, X, Y, and an array arr[] of size N, the task is to find the count of subarrays having at least X distinct elements that occur only Y times. Example: Input: N = 9, X = 2, Y = 2, arr[] = {2, 1, 2, 5, 3, 1, 3, 2, 5}Output:10Explanation:Subarrays with at least X distinct elements
    8 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
    CSES Solutions - Subarray Distinct Values
    Given an array of N integers arr[] and an integer K, your task is to calculate the number of subarrays that have at most K distinct values. Examples: Input: N = 5, K = 2, arr[] = {1, 2, 1, 2, 3}Output: 10Explanation: There are 12 subarrays with at most 2 distinct values: {1}, {2}, {1}, {2}, {3}, {1,
    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