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
JavaScript Program to Find Missing Characters to Make a String Pangram
We have given an input string and we need to find all the characters that are missing from the input string. We have to print all the output in the alphabetic order using JavaScript language. Below we have added the examples for better understanding. Examples: Input : welcome to geeksforgeeksOutput
6 min read
JavaScript - Check If a String Contains any Whitespace Characters
Here are the various methods to check if a string contains any whitespace characters using JavaScript.1. Using Regular ExpressionsThe most common and effective way to check for whitespace is by using a regular expression. The \s pattern matches any whitespace character.JavaScriptconst s = "Hello Wor
3 min read
Java Program to Print Smallest and Biggest Possible Palindrome Word in a Given String
A Palindrome String is a string whose reversed string is equal to the original string. In this Java Program, we are going to see the approach of printing the smallest and biggest palindrome word in a String. Given a sentence of words in the form of a string, and we need to print the smallest and lon
3 min read
Java Program to Print a New Line in String
Java is the most powerful programming language, by which we can perform many tasks and Java is an industry preferable language. So it is filled with a huge amount of features. Here we are going to discuss one of the best features of Java, that is how to print a new line in a string using Java. Metho
3 min read
Create a string with multiple spaces in JavaScript
We have a string with extra spaces and if we want to display it in the browser then extra spaces will not be displayed. Adding the number of spaces to the string can be done in the following ways. In this article, we are going to learn how to Create a string with multiple spaces in JavaScript. Below
3 min read
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 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
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 Swap Corner Words and Reverse Middle Characters of a String
Given a string containing n numbers of words. The task is to swap the corner words of the string and reverses all the middle characters of the string. Input: "Hello this is the GFG user" Output: "user GFG eth si siht Hello" Input: "Hello Bye" Output: "Bye Hello" Methods: Using the concept of ASCII v
5 min read