How to use Queue In Javascript
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:
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' ]
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
Table of Content
- Method 1: Using Recursion
- Method 2: Using Iteration
- Method 3: Using Bit Manipulation
- Method 4: Using Queue
Contact Us