Open In App

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

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



Input: 'abc'

Output:
abc 
ab 
ac 
a 
bc 
b 
c

Method 1: Using Recursion

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






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

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




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

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




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'
]

Article Tags :