JavaScript Program to Print all Possible Strings that can be Made by Placing Spaces
Last Updated :
06 Jun, 2024
In this article, We are going to see how can we print all possible strings that can be made by placing spaces. We will add spaces in between the strings and print every possible value.
Example:
Input: "ABCD"
Output: 'A B C D'
'A B CD'
'A BC D'
'A BCD'
'AB C D'
'AB CD'
'ABC D'
'ABCD'
By generating Permutations
- The idea is to use two methods, the first permutation method initializes an object and sorts the generated permutations.
- The second is solve method which is a recursive helper function that builds permutations by either including or excluding characters from the input string.
Example: This example shows the implementation of the above-explained approach.
JavaScript
class Solution {
permutation(s) {
let obj = { "k": [] };
this.solve(s, "", obj);
return obj["k"].sort();
}
solve(s, op, obj) {
if (s.length === 0) {
obj["k"].push(op);
return;
}
let ip = s[0];
s = s.slice(1);
this.solve(s, op + ip, obj);
if (op.length > 0) {
this.solve(s, op + " " + ip, obj);
}
}
}
const solution = new Solution();
const input = "ABC";
const result = solution.permutation(input);
console.log(result);
Output[ 'A B C', 'A BC', 'AB C', 'ABC' ]
Time Complexity: O(N!), where N is the length of the input string.
Space Complexity: O(N!), in worst case since the space grows with the number of permutations.
By placing spaces by Recursion
This code generates all permutations of a given string 's' using recursion. It starts with an empty output and two branches for each character in 's': one where the character is included in the current permutation and one where it's excluded (represented by adding a space). This process continues recursively until all permutations are generated and returned as an array.
Example: This example shows the implementation of the above-explained approach.
JavaScript
class Solution {
permutation(s) {
return this.subSet(s.charAt(0), s.slice(1));
}
subSet = (output, input) => {
let arr = [];
if (input.length == 0) {
arr.push(output);
return arr;
}
let output1 = output + input.charAt(0);
let output2 = output + " " + input.charAt(0);
arr =
arr.concat(this.subSet(output2, input.slice(1)));
arr =
arr.concat(this.subSet(output1, input.slice(1)));
return arr;
};
}
const solution = new Solution();
const input = "ABCD";
const result = solution.permutation(input);
console.log(result);
Output[
'A B C D', 'A B CD',
'A BC D', 'A BCD',
'AB C D', 'AB CD',
'ABC D', 'ABCD'
]
Time Complexity: O(N!), where N is the length of the input string.
Space Complexity: O(N!), in worst case since the space grows with the number of permutations.
By Recursion with Space Optimization
- The approach is to generate all possible permutations of a given string by recursively branching at each character, creating two options.
- One with the character joined to the previous characters and one with a space before the character.
- It continues this process for each character, and when it reaches the end, it adds the generated permutation to the result array.
- The final result is a sorted array of all possible permutations.
Example: This example shows the implementation of the above-explained approach.
JavaScript
class Solution {
permutation(s) {
if (s.length === 0) return [s];
const res = [];
let temp = '';
temp += s[0];
let input = s.slice(1);
const genPer = (temp, input) => {
if (input.length === 0) {
res.push(temp);
return;
}
let op1 = temp;
let op2 = temp;
op1 += input[0];
op2 += ' ' + input[0];
let clone = input.slice(1);
genPer(op1, clone);
genPer(op2, clone);
};
genPer(temp, input);
return res.sort();
}
}
const solution = new Solution();
const input = "ABC";
const result = solution.permutation(input);
console.log(result);
Output[ 'A B C', 'A BC', 'AB C', 'ABC' ]
Time Complexity: O(N!), where N is the length of the input string.
Space Complexity: O(N)
Using iterative methods
In this approach, we initialize the result array with an empty string. Then, for each character in the input string, we iterate through the current elements in the result array.
For each element in the result array, we append the current character both with and without a space. This way, we generate all possible strings by placing spaces between characters iteratively.
Finally, we return the result array containing all possible strings.
Example:
JavaScript
class Solution {
permutation(s) {
const result = ['']; // Start with an empty string
for (let i = 0; i < s.length; i++) {
const n = result.length;
for (let j = 0; j < n; j++) {
// Append current character without space
result.push(result[j] + s[i]);
// Append current character with space
result[j] += ' ' + s[i];
}
}
return result;
}
}
const solution = new Solution();
const input = "ABC";
const result = solution.permutation(input);
console.log(result);
Output[
' A B C', 'A B C',
' AB C', 'AB C',
' A BC', 'A BC',
' ABC', 'ABC'
]
Similar Reads
Java Program to Separate the Individual Characters from a String The string is a sequence of characters including spaces. Objects of String are immutable in java, which means that once an object is created in a string, it's content cannot be changed. In this particular problem statement, we are given to separate each individual characters from the string provided
2 min read
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
Program to replace every space in a string with hyphen Given a string, the task is to replace all the spaces between the words with a hyphen character '-'. Examples: Input: str = "Geeks for Geeks." Output: Geeks-for-Geeks. Input: str = "A computer science portal for geeks" Output: A-computer-science-portal-for-geeks Approach: Traverse the whole string c
6 min read
Java Program to Check Whether the String Consists of Special Characters In Java, special characters refer to symbols other than letters and digits, such as @, #, !, etc. To check whether the String consists of special characters, there are multiple ways, including using the Character class, regular expressions, or simple string checks.Example:In this example, we will us
4 min read
How to Handle Multiple String Inputs with Spaces in C++? In C++, strings are a sequence of characters that might contain spaces in many cases but we can read only the input text till whitespace using cin. In this article, we will learn how to handle multiple string inputs with spaces in C++. Example: Input:Enter multiple strings:String1String2Output:You E
2 min read