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 Print all Subsequences of a String
Next article icon

JavaScript Program to Print all Subsequences of a String

Last Updated : 27 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 method.

Example: The example shows the input string and the corresponding output

Input: 'abc'  Output: abc  ab  ac  a  bc  b  c 

Table of Content

  • Method 1: Using Recursion
  • Method 2: Using Iteration
  • Method 3: Using Bit Manipulation
  • Method 4: Using Queue

Method 1: Using Recursion

  • We can recursively generate subsequences by including or excluding each character in the string.
  • Create a function generateSubsequence with two parameters input and output.
  • Check input.length==0 by using if condition.
  • Here, value of inputString= "abc".
  • Then, call the function generateSubsequence.

Example: This example prints all subsequences of a string in JavaScript using the Recursion method.

JavaScript
function generateSubsequence(input, output) {     // Base Case     if (input.length==0) {         console.log(output);         return;     }     // Include     generateSubsequence(         input.substring(1), output + input[0]);          // Exclude     generateSubsequence(         input.substring(1), output); } const inputString = 'abc'; generateSubsequence(inputString,""); 

Output
abc ab ac a bc b c 

Method 2: Using Iteration

  • We can use iterative methods to generate all possible combinations of characters in the string.
  • Create a function generateSubsequence with one parameter input.
  • Inside the function store the length of the input in variable length. Iterate and check conditions by using for loop and if condition respectively.
  • Here, the value of inputString= "abc".
  • Then, call the function generateSubsequence with argument inputstring to get output.

Example: This example prints all subsequences of a string in JavaScript using the Iteration method.

JavaScript
function generateSubsequences(input) {     const subsequences = [];     const length = input.length;      for (         let i = 0;         i < 1 << length;         i++     ) {         let currentSubsequence = "";          for (             let j = 0;             j < length;             j++         ) {             if (i & (1 << j)) {                 currentSubsequence +=                     input[j];             }         }          subsequences.push(             currentSubsequence         );     }      return subsequences; }  const inputString = "abc"; const allSubsequences =     generateSubsequences(inputString); console.log(allSubsequences); 

Output
[   '',   'a',   'b',   'ab', 'c',   'ac',   'bc', 'abc' ] 

Method 3: Using Bit Manipulation

  • We can use bit manipulation to represent the inclusion or exclusion of each character in the subsequence.
  • Create a function generateSubsequence with one parameter input.
  • Inside the function store the length of the input in variable length. Iterate and check conditions by using for loop and if condition respectively.
  • Here,the value of inputString= "abc".
  • Then, call the function generateSubsequence with argument inputstring to get output.

Example: This example prints all subsequences of a string in JavaScript using the Bit manipulation method.

JavaScript
function generateSubsequences(input) {     const subsequences = [];     const length = input.length;      for (         let mask = 0;         mask < 1 << length;         mask++     ) {         let currentSubsequence = "";          for (             let bit = 0;             bit < length;             bit++         ) {             if (mask & (1 << bit)) {                 currentSubsequence +=                     input[bit];             }         }          subsequences.push(             currentSubsequence         );     }      return subsequences; }  const inputString = "abc"; const allSubsequences =     generateSubsequences(inputString); console.log(allSubsequences); 

Output
[   '',   'a',   'b',   'ab', 'c',   'ac',   'bc', 'abc' ] 

Method 4: Using Queue

Using a queue, iteratively generate subsequences by appending each character to existing subsequences. Initially, the queue contains an empty string. For each character in the string, append it to each string in the queue and enqueue the result.

Example:

JavaScript
function printSubsequences(str) {   const queue = [''];   for (const char of str) {     const size = queue.length;     for (let i = 0; i < size; i++) {       queue.push(queue[i] + char);     }   }   console.log(queue); }  printSubsequences("abcd"); 

Output
[   '',     'a',   'b',   'ab',   'c',   'ac',   'bc',   'abc', 'd',   'ad',   'bd',  'abd',   'cd',   'acd', 'bcd',   'abcd' ] 



Next Article
JavaScript Program to Print all Subsequences of a String

A

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

Similar Reads

    Java Program to Print all Unique Words of a String
    Java program to print all unique words present in the string. The task is to print all words occurring only once in the string. Illustration: Input : Welcome to Geeks for Geeks. Output : Welcome to for Input : Java is great.Python is also great. Output : Java Python also Methods: This can be done in
    4 min read
    Java Program to Find All Palindromic Sub-Strings of a String
    Given a string, the task is to count all palindrome substring in a given string. Input : aba Output : 4 Explanation : All palindrome substring are : "aba" , "a" , "b", "a" Input : TENET Output : 7 Explanation : All palindrome sub-string are : "T" , "E" , "N", "E", "T" , "ENE" , "TENET" Approach: Tak
    2 min read
    Javascript Program for Longest subsequence of a number having same left and right rotation
    Given a numeric string S, the task is to find the maximum length of a subsequence having its left rotation equal to its right rotation. Examples: Input: S = "100210601" Output: 4 Explanation: The subsequence "0000" satisfies the necessary condition. The subsequence "1010" generates the string "0101"
    4 min read
    Construct string having all possible strings of K letters as subsequence
    Given two positive integers, let's denote them as N and K. The task is to construct a string S such that all possible strings of length N formed using the first K lowercase English alphabets, appear as subsequences of S. In case there exist multiple valid solutions, the objective is to output the so
    4 min read
    C# - Different Ways to Find All Substrings in a String
    Given a string as an input we need to find all the substrings present in the given string. Example: Input: geeks Output: g e e k s ge ee ek ks gee eek eks geek eeks geeks Input: ab Output: a b abMethod 1: Using Substring() method We can find all the substrings from the given string using the Substri
    3 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