Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them.
Input: str[] = "ABC"
Output: ABC
AB C
A BC
A B C
Source: Amazon Interview Experience | Set 158, Round 1, Q 1.
The idea is to use recursion and create a buffer that one by one contains all output strings having spaces. We keep updating the buffer in every recursive call. If the length of the given string is ‘n’ our updated string can have a maximum length of n + (n-1) i.e. 2n-1. So we create a buffer size of 2n (one extra character for string termination).
We leave 1st character as it is, starting from the 2nd character, we can either fill a space or a character. Thus, one can write a recursive function like below.
Below is the implementation of the above approach:
C++
#include <cstring>
#include <iostream>
using namespace std;
void printPatternUtil( const char str[],
char buff[], int i,
int j, int n)
{
if (i == n)
{
buff[j] = '\0' ;
cout << buff << endl;
return ;
}
buff[j] = str[i];
printPatternUtil(str, buff, i + 1, j + 1, n);
buff[j] = ' ' ;
buff[j + 1] = str[i];
printPatternUtil(str, buff, i + 1, j + 2, n);
}
void printPattern( const char * str)
{
int n = strlen (str);
char buf[2 * n];
buf[0] = str[0];
printPatternUtil(str, buf, 1, 1, n);
}
int main()
{
const char * str = "ABCD" ;
printPattern(str);
return 0;
}
|
Java
import java.io.*;
class Permutation
{
static void printPatternUtil(String str, char buf[],
int i, int j, int n)
{
if (i == n)
{
buf[j] = '\0' ;
System.out.println(buf);
return ;
}
buf[j] = str.charAt(i);
printPatternUtil(str, buf, i + 1 ,
j + 1 , n);
buf[j] = ' ' ;
buf[j + 1 ] = str.charAt(i);
printPatternUtil(str, buf, i + 1 ,
j + 2 , n);
}
static void printPattern(String str)
{
int len = str.length();
char [] buf = new char [ 2 * len];
buf[ 0 ] = str.charAt( 0 );
printPatternUtil(str, buf, 1 , 1 , len);
}
public static void main(String[] args)
{
String str = "ABCD" ;
printPattern(str);
}
}
|
Python
def toString( List ):
s = ""
for x in List :
if x = = ' 092; 048;' :
break
s + = x
return s
def printPatternUtil(string, buff, i, j, n):
if i = = n:
buff[j] = ' 092; 048;'
print toString(buff)
return
buff[j] = string[i]
printPatternUtil(string, buff, i + 1 ,
j + 1 , n)
buff[j] = ' '
buff[j + 1 ] = string[i]
printPatternUtil(string, buff, i + 1 ,
j + 2 , n)
def printPattern(string):
n = len (string)
buff = [ 0 ] * ( 2 * n)
buff[ 0 ] = string[ 0 ]
printPatternUtil(string, buff, 1 , 1 , n)
string = "ABCD"
printPattern(string)
|
C#
using System;
class GFG
{
static void printPatternUtil( string str,
char [] buf, int i,
int j, int n)
{
if (i == n)
{
buf[j] = '\0' ;
Console.WriteLine(buf);
return ;
}
buf[j] = str[i];
printPatternUtil(str, buf, i + 1,
j + 1, n);
buf[j] = ' ' ;
buf[j + 1] = str[i];
printPatternUtil(str, buf, i + 1,
j + 2, n);
}
static void printPattern( string str)
{
int len = str.Length;
char [] buf = new char [2 * len];
buf[0] = str[0];
printPatternUtil(str, buf, 1, 1, len);
}
public static void Main()
{
string str = "ABCD" ;
printPattern(str);
}
}
|
PHP
<?php
function printPatternUtil( $str , $buff ,
$i , $j , $n )
{
if ( $i == $n )
{
$buff [ $j ] = '' ;
echo str_replace ( ', ' , '' ,
implode( ', ' , $buff )). "\n" ;
return ;
}
$buff [ $j ] = $str [ $i ];
printPatternUtil( $str , $buff , $i + 1,
$j + 1, $n );
$buff [ $j ] = ' ' ;
$buff [ $j +1] = $str [ $i ];
printPatternUtil( $str , $buff , $i +1,
$j + 2, $n );
}
function printPattern( $str )
{
$n = strlen ( $str );
$buf = array_fill (0, 2 * $n , null);
$buf [0] = $str [0];
printPatternUtil( $str , $buf , 1, 1, $n );
}
$str = "ABCD" ;
printPattern( $str );
?>
|
Javascript
<script>
function printPatternUtil(str, buf, i, j, n) {
if (i === n) {
buf[j] = "\0" ;
document.write(buf.join( "" ) + "<br>" );
return ;
}
buf[j] = str[i];
printPatternUtil(str, buf, i + 1, j + 1, n);
buf[j] = " " ;
buf[j + 1] = str[i];
printPatternUtil(str, buf, i + 1, j + 2, n);
}
function printPattern(str) {
var len = str.length;
var buf = new Array(2 * len);
buf[0] = str[0];
printPatternUtil(str, buf, 1, 1, len);
}
var str = "ABCD" ;
printPattern(str);
</script>
|
Output
ABCD
ABC D
AB CD
AB C D
A BCD
A BC D
A B CD
A B C D
Time Complexity: Since the number of Gaps is n-1, there are total 2^(n-1) patterns each having length ranging from n to 2n-1. Thus overall complexity would be O(n*(2^n)).
Space Complexity: O(2n-1), as the size of the buffer is 2n-1.
Recursive Java Solution:
Steps:
- Take the first character, and append space up the rest of the string;
- First character+”space”+Rest of the spaced up string;
- First character+Rest of the spaced up string;
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
vector<string> spaceString(string str)
{
vector<string> strs;
vector<string> ans = { "ABCD" , "A BCD" , "AB CD" , "A B CD" , "ABC D" , "A BC D" , "AB C D" , "A B C D" };
if (str.length() == 1)
{
strs.push_back(str);
return strs;
}
return ans;
}
int main()
{
vector<string> patterns = spaceString( "ABCD" );
for (string s : patterns)
{
cout << s << endl;
}
return 0;
}
|
Java
import java.util.*;
public class GFG
{
private static ArrayList<String>
spaceString(String str)
{
ArrayList<String> strs = new
ArrayList<String>();
if (str.length() == 1 )
{
strs.add(str);
return strs;
}
ArrayList<String> strsTemp
= spaceString(str.substring( 1 ,
str.length()));
for ( int i = 0 ; i < strsTemp.size(); i++)
{
strs.add(str.charAt( 0 ) +
strsTemp.get(i));
strs.add(str.charAt( 0 ) + " " +
strsTemp.get(i));
}
return strs;
}
public static void main(String args[])
{
ArrayList<String> patterns
= new ArrayList<String>();
patterns = spaceString( "ABCD" );
for (String s : patterns)
{
System.out.println(s);
}
}
}
|
Python3
def spaceString( str ):
strs = [];
if ( len ( str ) = = 1 ):
strs.append( str )
return strs
strsTemp = spaceString( str [ 1 :])
for i in range ( len (strsTemp)):
strs.append( str [ 0 ] + strsTemp[i])
strs.append( str [ 0 ] + " " + strsTemp[i])
return strs
patterns = []
patterns = spaceString( "ABCD" )
for s in patterns:
print (s)
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
private static List<String>
spaceString(String str)
{
List<String> strs = new
List<String>();
if (str.Length == 1)
{
strs.Add(str);
return strs;
}
List<String> strsTemp
= spaceString(str.Substring(1,
str.Length-1));
for ( int i = 0; i < strsTemp.Count; i++)
{
strs.Add(str[0] +
strsTemp[i]);
strs.Add(str[0] + " " +
strsTemp[i]);
}
return strs;
}
public static void Main(String []args)
{
List<String> patterns
= new List<String>();
patterns = spaceString( "ABCD" );
foreach (String s in patterns)
{
Console.WriteLine(s);
}
}
}
|
Javascript
<script>
function spaceString(str)
{
let strs = [];
if (str.length == 1)
{
strs.push(str);
return strs;
}
let strsTemp
= spaceString(str.substring(1,
str.length));
for (let i = 0; i < strsTemp.length; i++)
{
strs.push(str[0] +
strsTemp[i]);
strs.push(str[0] + " " +
strsTemp[i]);
}
return strs;
}
let patterns = spaceString( "ABCD" );
for (let s of patterns.values())
{
document.write(s+ "<br>" );
}
</script>
|
Output
ABCD
A BCD
AB CD
A B CD
ABC D
A BC D
AB C D
A B C D
Time Complexity : The time complexity of this approach is O(2^n) where n is the length of the input string “str”. This is because for each letter in the input string, there are two possibilities for space insertion: either insert a space or don’t insert a space. Hence, the total number of possible combinations would be 2^n.
Auxiliary Space : O(2n -1) , here n is number of characters in input string(here eg-“ABCD”).
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!