Print all possible strings that can be made by placing spaces

Last Updated : 14 Jan, 2026

Given a string s of length n, the task is to find all the possible strings that can be made by placing space ( 0 or 1) in between the characters of the input string.

Examples:

Input: s = "ABC"
Output:
A B C
A BC
AB C
ABC
Explanation: Place spaces between each character first, then place single space between single and pair of characters.

Input: s = "A"
Output:
A
Explanation: There is only a single element hence we'll get a single output.

Try It Yourself
redirect icon

Source: Amazon Interview Experience | Set 158, Round 1, Q 1. 

[Approach] Recursive Approach

The idea is to use recursion where at each position (except the first), we make two choices: either add a space before the current character or don't add a space, and recursively build all possible combinations.

Step by step Implementation :

  • Start with the first character in the current string since no space can be placed before it.
  • For each subsequent indices, make two recursive calls: one adding space before character and one without space.
  • When we reach the end of the original string, add the current built string to the result.
  • Use backtracking by removing the last added characters when returning from recursion.
C++
// C++ program to Print all possible strings 
// that can be made by placing spaces
#include <bits/stdc++.h>
using namespace std;

void permutationRecur(string &s, int i, string curr, vector<string> &res) {
    
    // Base Case: End of string 
    if (i == s.length()) {
        res.push_back(curr);
        return;
    }
    
    // Choice 1: Add space before curr character
    permutationRecur(s, i + 1, curr + " " + s[i], res);
    
    // Choice 2: Don't add space
    permutationRecur(s, i + 1, curr + s[i], res);
}

vector<string> permutation(string &s) {
    vector<string> res;
    
    string curr = "";
    
    // For i 0, we only have the option 
    // to add the character 
    curr += s[0];
    
    permutationRecur(s, 1, curr, res);
    return res;
}

int main() {
    string s = "ABC";
    vector<string> res = permutation(s);
    for (string str: res) cout << str << endl;
    return 0;
}
Java
// Java program to Print all possible strings 
// that can be made by placing spaces

import java.util.ArrayList;

class GfG {
    static void permutationRecur(String s, int i, String curr,
    ArrayList<String> res) {
        
        // Base Case: End of string 
        if (i == s.length()) {
            res.add(curr);
            return;
        }
        
        // Choice 1: Add space before curr character
        permutationRecur(s, i + 1, curr + " " + s.charAt(i), res);
        
        // Choice 2: Don't add space
        permutationRecur(s, i + 1, curr + s.charAt(i), res);
    }

    static ArrayList<String> permutation(String s) {
        ArrayList<String> res = new ArrayList<>();
        
        String curr = "";
        
        // For i 0, we only have the option 
        // to add the character 
        curr += s.charAt(0);
        
        permutationRecur(s, 1, curr, res);
        return res;
    }

    public static void main(String[] args) {
        String s = "ABC";
        ArrayList<String> res = permutation(s);
        for (String str: res) System.out.println(str);
    }
}
Python
# Python program to Print all possible strings 
# that can be made by placing spaces

def permutationRecur(s, i, curr, res):
    
    # Base Case: End of string 
    if i == len(s):
        res.append(curr)
        return
    
    # Choice 1: Add space before curr character
    permutationRecur(s, i + 1, curr + " " + s[i], res)
    
    # Choice 2: Don't add space
    permutationRecur(s, i + 1, curr + s[i], res)

def permutation(s):
    res = []
    
    curr = ""
    
    # For i 0, we only have the option 
    # to add the character 
    curr += s[0]
    
    permutationRecur(s, 1, curr, res)
    return res

if __name__ == "__main__":
    s = "ABC"
    res = permutation(s)
    for str in res: print(str)
C#
// C# program to Print all possible strings 
// that can be made by placing spaces

using System;
using System.Collections.Generic;

class GfG {
    static void permutationRecur(string s, int i, string curr, List<string> res) {
        
        // Base Case: End of string 
        if (i == s.Length) {
            res.Add(curr);
            return;
        }
        
        // Choice 1: Add space before curr character
        permutationRecur(s, i + 1, curr + " " + s[i], res);
        
        // Choice 2: Don't add space
        permutationRecur(s, i + 1, curr + s[i], res);
    }

    static List<string> permutation(string s) {
        List<string> res = new List<string>();
        
        string curr = "";
        
        // For i 0, we only have the option 
        // to add the character 
        curr += s[0];
        
        permutationRecur(s, 1, curr, res);
        return res;
    }

    static void Main() {
        string s = "ABC";
        List<string> res = permutation(s);
        foreach (string str in res) Console.WriteLine(str);
    }
}
JavaScript
// JavaScript program to Print all possible strings 
// that can be made by placing spaces

function permutationRecur(s, i, curr, res) {
    
    // Base Case: End of string 
    if (i === s.length) {
        res.push(curr);
        return;
    }
    
    // Choice 1: Add space before curr character
    permutationRecur(s, i + 1, curr + " " + s[i], res);
    
    // Choice 2: Don't add space
    permutationRecur(s, i + 1, curr + s[i], res);
}

function permutation(s) {
    let res = [];
    
    let curr = "";
    
    // For i 0, we only have the option 
    // to add the character 
    curr += s[0];
    
    permutationRecur(s, 1, curr, res);
    return res;
}

let s = "ABC";
let res = permutation(s);
for (let str of res) console.log(str);

Output
A B C
A BC
AB C
ABC

Time Complexity: O(2^(n-1) * n), where n is the length of string and there are 2^(n-1) possible strings.
Auxiliary Space: O(2^(n-1) * n) to store the strings.

[Approach] Using Dynamic Programming

The main idea is to build all valid strings by iteratively placing a space or no space between characters, storing intermediate results in a 2D array. At each step, every previous string generates two new strings: one with a space before the current character, and one without.

C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<string> permutation(string s) {
    int n = s.size();
    vector<vector<string>> dp(n);

    dp[0].push_back(string(1, s[0]));

    for (int i = 1; i < n; ++i) {
        for (string prev : dp[i - 1]) {
            
            // Adding space around
            dp[i].push_back(prev + " " + s[i]);  
            
            // Avoiding Space
            dp[i].push_back(prev + s[i]);        
        }
    }

    return dp[n - 1];
}

int main() {
    string s = "ABC";
    vector<string> res = permutation(s);
    for (const string &str : res) {
        cout << str << endl;
    }
    return 0;
}
Java
public class GfG {

    public static String[] permutation(String s) {
        int n = s.length();
        
        // Use an array of arrays to simulate dp table
        String[][] dp = new String[n][];
        
        dp[0] = new String[] { String.valueOf(s.charAt(0)) };

        for (int i = 1; i < n; ++i) {
            String[] prev = dp[i - 1];
            int prevLen = prev.length;

            // Each string generates two possibilities: with and without space
            String[] curr = new String[prevLen * 2];
            int index = 0;

            for (int j = 0; j < prevLen; ++j) {
                String p = prev[j];

                // Adding space around
                curr[index++] = p + " " + s.charAt(i);

                // Avoiding Space
                curr[index++] = p + s.charAt(i);
            }

            dp[i] = curr;
        }

        return dp[n - 1];
    }

    public static void main(String[] args) {
        String s = "ABC";
        String[] res = permutation(s);
        for (int i = 0; i < res.length; i++) {
            System.out.println(res[i]);
        }
    }
}
Python
def permutation(s):
    n = len(s)
    
    dp = [[] for _ in range(n)]
    
    dp[0] = [s[0]]

    for i in range(1, n):
        prev = dp[i - 1]
        curr = ["" for _ in range(len(prev) * 2)]
        idx = 0

        for j in range(len(prev)):
            p = prev[j]

            # Adding space around
            curr[idx] = p + " " + s[i]
            idx += 1

            # Avoiding Space
            curr[idx] = p + s[i]
            idx += 1

        dp[i] = curr

    return dp[n - 1]

if __name__ == "__main__":
    s = "ABC"
    res = permutation(s)
    for r in res:
        print(r)
C#
using System;

class GfG {
    const int MAX_RESULTS = 1024; 
    const int MAX_LEN = 100;      

    static void permutation(string s, out string[] res, out int resCount) {
        int n = s.Length;
        string[,] dp = new string[n, MAX_RESULTS];
        int[] count = new int[n]; 

        // Base case: only first character
        dp[0, 0] = s[0].ToString();
        count[0] = 1;

        for (int i = 1; i < n; ++i) {
            int k = 0;
            for (int j = 0; j < count[i - 1]; ++j) {
                string prev = dp[i - 1, j];

                // Adding space around
                dp[i, k++] = prev + " " + s[i];

                // Avoiding space
                dp[i, k++] = prev + s[i];
            }
            count[i] = k;
        }

        resCount = count[n - 1];
        res = new string[resCount];
        for (int i = 0; i < resCount; ++i)
        {
            res[i] = dp[n - 1, i];
        }
    }

    static void Main() {
        string s = "ABC";
        permutation(s, out string[] results, out int total);

        for (int i = 0; i < total; i++) {
            Console.WriteLine(results[i]);
        }
    }
}
JavaScript
function permutation(s) {
    const n = s.length;
    const MAX_RESULTS = 1024;  
    const dp = Array.from({ length: n }, () => new Array(MAX_RESULTS).fill(""));
    const count = new Array(n).fill(0);

    // Base case: dp[0] = first character
    dp[0][0] = s[0];
    count[0] = 1;

    for (let i = 1; i < n; ++i) {
        let k = 0;
        for (let j = 0; j < count[i - 1]; ++j) {
            const prev = dp[i - 1][j];

            // Adding space around
            dp[i][k++] = prev + " " + s[i];

            // Avoiding Space
            dp[i][k++] = prev + s[i];
        }
        count[i] = k;
    }

    const resCount = count[n - 1];
    const result = new Array(resCount);
    for (let i = 0; i < resCount; ++i) {
        result[i] = dp[n - 1][i];
    }

    return result;
}

// Driver Code
const s = "ABC";
const output = permutation(s);
for (let i = 0; i < output.length; ++i) {
    console.log(output[i]);
}

Output
A B C
A BC
AB C
ABC

Time Complexity : O(2^n * n)
Auxiliary Space : O(2^n * n)


Comment