Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Print all palindromic partitions of a string

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given a string s, partition s such that every string of the partition is a palindrome. Return all possible palindrome partitioning of s. 

Example : 

Input  : s = "bcc"
Output : [["b", "c", "c"], ["b", "cc"]]

Input  : s = "geeks"
Output : [["g", "e", "e", "k", "s"], 
          ["g", "ee", "k", "s"]]

Easy to Understand And StraightForward Approach(Backtracking):

The Approach: In this approach, we try over all partitions recursively.

C++




#include <bits/stdc++.h>
#include <iostream>
using namespace std;
 
bool check_palindrome(string s, int index, int i)
{
    while (index <= i) {
        if (s[index++] != s[i--])
            return 0;
    }
    return 1;
}
// by refer
void the_helper(vector<vector<string> >& result,
                vector<string>& dump, string s, int n,
                int index)
{
    // base case avoid >= because here we need only unique
    // combination not repeating just 1 at 2 and 2 at 1.
    if (index == n) {
        result.push_back(dump);
        return;
    }
    // main worker of the program.
    for (int i = index; i < n; i++) {
        // if s.substr till i from index is palindrome.
        if (check_palindrome(s, index, i)) {
            dump.push_back(s.substr(index, i - index + 1));
            the_helper(result, dump, s, n, i + 1);
            // backtracting.
            dump.pop_back();
        }
    }
}
int main()
{
    string s = "bcc";
    // size of string.
    int n = s.size();
    // where all possible partitions we store.
    vector<vector<string> > result;
    // for temporary storage.
    vector<string> dump;
    // The Helper function call.
    the_helper(result, dump, s, n, 0);
    int row_l = result.size();
    cout << "All Possible palindromic partitions of a "
            "string : "
         << endl;
    cout << "[";
    for (int i = 0; i < row_l; i++) {
        cout << "[";
        int m = result[i].size();
        for (int j = 0; j < m; j++) {
            if (j == m - 1) {
                cout << result[i][j];
                continue;
            }
            cout << result[i][j] << ",";
        }
        if (i == row_l - 1) {
            cout << "]";
            continue;
        }
        cout << "],";
    }
    cout << "]";
    // code by Sanket Gode
    return 0;
}


Java




// Java equivalent code with similar comments
 
// Importing required libraries
import java.util.ArrayList;
import java.util.List;
 
public class PalindromePartition {
// Check if the string from index to i is a palindrome
public static boolean checkPalindrome(String s, int index, int i) {
while (index <= i) {
if (s.charAt(index) != s.charAt(i)) {
return false;
}
index++;
i--;
}
return true;
}
  public static void theHelper(List<List<String>> result, List<String> dump, String s, int n, int index) {
    // Base case: when the end of string is reached, add the possible partition to result
    if (index == n) {
        result.add(new ArrayList<>(dump));
        return;
    }
 
    // Main worker function
    for (int i = index; i < n; i++) {
        // If the string from index to i is a palindrome
        if (checkPalindrome(s, index, i)) {
            dump.add(s.substring(index, i + 1));
            theHelper(result, dump, s, n, i + 1);
            // Backtracking
            dump.remove(dump.size() - 1);
        }
    }
}
 
public static List<List<String>> allPalindromePartitions(String s) {
    // Store all possible partitions
    List<List<String>> result = new ArrayList<>();
    // Temporary storage
    List<String> dump = new ArrayList<>();
    int n = s.length();
    // Call the helper function
    theHelper(result, dump, s, n, 0);
    return result;
}
 
public static void main(String[] args) {
    // Testing
    String s = "bcc";
    List<List<String>> result = allPalindromePartitions(s);
    System.out.println("All Possible palindromic partitions of the string:");
    System.out.println(result);
}
}
 
//This code is contributed by shivamsharma215


Python3




# Python equivalent code with comments
 
# Importing required libraries
from typing import List, Tuple
 
def check_palindrome(s: str, index: int, i: int) -> bool:
    # Check if the string from index to i is a palindrome
    while index <= i:
        if s[index] != s[i]:
            return False
        index += 1
        i -= 1
    return True
 
def the_helper(result: List[List[str]], dump: List[str], s: str, n: int, index: int):
    # Base case: when the end of string is reached, add the possible partition to result
    if index == n:
        result.append(dump[:])
        return
 
    # Main worker function
    for i in range(index, n):
        # If the string from index to i is a palindrome
        if check_palindrome(s, index, i):
            dump.append(s[index:i+1])
            the_helper(result, dump, s, n, i+1)
            # Backtracking
            dump.pop()
 
def all_palindrome_partitions(s: str) -> List[List[str]]:
    # Store all possible partitions
    result = []
    # Temporary storage
    dump = []
    n = len(s)
    # Call the helper function
    the_helper(result, dump, s, n, 0)
    return result
 
# Testing
s = "bcc"
result = all_palindrome_partitions(s)
print("All Possible palindromic partitions of the string:")
print(result)
 
# This code is contributed by Vikram_Shirsat


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program {
    static bool CheckPalindrome(string s, int index, int i)
    {
        while (index <= i) {
            if (s[index++] != s[i--])
                return false;
        }
        return true;
    }
    static void TheHelper(List<List<string> > result,
                          List<string> dump, string s,
                          int n, int index)
    {
        // Base case avoid >= because here we need only
        // unique combination not repeating just 1 at 2 and
        // 2 at 1.
        if (index == n) {
            result.Add(new List<string>(dump));
            return;
        }
 
        // Main worker of the program.
        for (int i = index; i < n; i++) {
            // If s.Substring till i from index is
            // palindrome.
            if (CheckPalindrome(s, index, i)) {
                dump.Add(s.Substring(index, i - index + 1));
                TheHelper(result, dump, s, n, i + 1);
                // Backtracting.
                dump.RemoveAt(dump.Count - 1);
            }
        }
    }
 
    static void Main(string[] args)
    {
        string s = "bcc";
        // Size of string.
        int n = s.Length;
        // Where all possible partitions we store.
        List<List<string> > result
            = new List<List<string> >();
        // For temporary storage.
        List<string> dump = new List<string>();
        // The Helper function call.
        TheHelper(result, dump, s, n, 0);
        int row_l = result.Count;
        Console.Write(
            "All Possible palindromic partitions of a string : ");
        Console.Write("[");
        for (int i = 0; i < row_l; i++) {
            Console.Write("[");
            int m = result[i].Count;
            for (int j = 0; j < m; j++) {
                if (j == m - 1) {
                    Console.Write(result[i][j]);
                    continue;
                }
                Console.Write(result[i][j] + ",");
            }
            if (i == row_l - 1) {
                Console.Write("]");
                continue;
            }
            Console.Write("],");
        }
        Console.Write("]");
    }
}


Javascript




function checkPalindrome(s, index, i) {
  while (index <= i) {
    if (s.charAt(index) !== s.charAt(i)) {
      return false;
    }
    index++;
    i--;
  }
  return true;
}
 
function theHelper(result, dump, s, n, index)
{
 
  // Base case: when the end of string is reached,
  // add the possible partition to result
  if (index === n) {
    result.push(dump.slice());
    return;
  }
 
  // Main worker function
  for (let i = index; i < n; i++) {
    // If the string from index to i is a palindrome
    if (checkPalindrome(s, index, i)) {
      dump.push(s.substring(index, i + 1));
      theHelper(result, dump, s, n, i + 1);
      // Backtracking
      dump.pop();
    }
  }
}
 
function allPalindromePartitions(s)
{
 
  // Store all possible partitions
  const result = [];
   
  // Temporary storage
  const dump = [];
  const n = s.length;
   
  // Call the helper function
  theHelper(result, dump, s, n, 0);
  return result;
}
 
// Testing
const s = "bcc";
const result = allPalindromePartitions(s);
console.log("All Possible palindromic partitions of the string:");
console.log(result);


Output

All Possible palindromic partitions of a string : 
[[b,c,c],[b,cc]]

Complexity Analysis:

Time Complexity: O(2*n).(backtracking).

Space Complexity: O(n*2).

We have to list the all possible partitions so we will think in the direction of recursion. When we are on index i, we incrementally check all substrings starting from i for being palindromic. If found, we recursively solve the problem for the remaining string and add this in our solution. 

Following is the solution-

  1. We will maintain a 2-dimensional vector for storing all possible partitions and a temporary vector for storing the current partition, new starting index of string to check partitions as we have already checked partitions before this index.
  2. Now keep on iterating further on string and check if it is palindrome or not.
  3. If it is a palindrome than add this string in current partitions vector. Recurse on this new string if it is not the end of the string. After coming back again change the current partition vector to the old one as it might have changed in the recursive step.
  4. If we reach the end of string while iterating than we have our partitions in our temporary vector so we will add it in results.

To check whether it’s a palindrome or not, iterate on string by taking two pointers. Initialize the first to start and other to end of string. If both characters are same increase the first and decrease the last pointer and keep on iterating until first is less than last one. 

Implementation:

C++




// C++ program to print all palindromic partitions
// of a given string.
#include <bits/stdc++.h>
using namespace std;
 
// Returns true if str is palindrome, else false
bool checkPalindrome(string str)
{
    int len = str.length();
    len--;
    for (int i=0; i<len; i++)
    {
        if (str[i] != str[len])
            return false;
        len--;
    }
    return true;
}
 
void printSolution(vector<vector<string> > partitions)
{
    for (int i = 0; i < partitions.size(); ++i)
    {
        for(int j = 0; j < partitions[i].size(); ++j)
            cout << partitions[i][j] << " ";
        cout << endl;
    }
    return;
}
 
// Goes through all indexes and recursively add remaining
// partitions if current string is palindrome.
void addStrings(vector<vector<string> > &v, string &s,
                vector<string> &temp, int index)
{
    int len = s.length();
    string str;
    vector<string> current = temp;
    if (index == 0)
        temp.clear();
    for (int i = index; i < len; ++i)
    {
        str = str + s[i];
        if (checkPalindrome(str))
        {
            temp.push_back(str);
            if (i+1 < len)
                addStrings(v,s,temp,i+1);
            else
                v.push_back(temp);
            temp = current;
        }
    }
    return;
}
 
// Generates all palindromic partitions of 's' and
// stores the result in 'v'.
void partition(string s, vector<vector<string> >&v)
{
    vector<string> temp;
    addStrings(v, s, temp, 0);
    printSolution(v);
    return;
}
 
// Driver code
int main()
{
    string s = "geeks";
    vector<vector<string> > partitions;
    partition(s, partitions);
    return 0;
}


Java




// Java program to print all palindromic partitions
// of a given string.
import java.util.ArrayList;
public class GFG
{    
    // Returns true if str is palindrome, else false
    static boolean checkPalindrome(String str)
    {
        int len = str.length();
        len--;
        for (int i=0; i<len; i++)
        {
            if (str.charAt(i) != str.charAt(len))
                return false;
            len--;
        }
        return true;
    }
     
    // Prints the partition list
    static void printSolution(ArrayList<ArrayList<String>>
                                          partitions)
    {
        for(ArrayList<String> i: partitions)
        {
            for(String j: i)
            {
                System.out.print(j+" ");
            }
            System.out.println();
        }
    }
      
    // Goes through all indexes and recursively add remaining
    // partitions if current string is palindrome.
    static ArrayList<ArrayList<String>> addStrings(ArrayList<
       ArrayList<String>> v, String s, ArrayList<String> temp,
                                             int index)
    {
        int len = s.length();
        String str = "";
        ArrayList<String> current = new ArrayList<>(temp);
         
        if (index == 0)
            temp.clear();
         
        // Iterate over the string
        for (int i = index; i < len; ++i)
        {
            str = str + s.charAt(i);
             
            // check whether the substring is
            // palindromic or not
            if (checkPalindrome(str))
            {
                // if palindrome add it to temp list
                temp.add(str);
                 
                if (i + 1 < len)
                {   
                    // recur to get all the palindromic
                    // partitions for the substrings
                    v = addStrings(v,s,temp,i+1);
                }
                else
                {
                    // if end of the string is reached
                    // add temp to v
                    v.add(temp);
                }
                 
                // temp is reinitialize with the
                // current i.
                temp = new ArrayList<>(current);
            }
        }
        return v;
    }
      
    // Generates all palindromic partitions of 's' and
    // stores the result in 'v'.
    static void partition(String s, ArrayList<ArrayList<
                                          String>> v)
    {
        // temporary ArrayList to store each
        // palindromic string
        ArrayList<String> temp = new ArrayList<>();
         
        // calling addString method it adds all 
        // the palindromic partitions to v
        v = addStrings(v, s, temp, 0);
         
        // printing the solution
        printSolution(v);
    }
      
    // Driver code
    public static void main(String args[])
    {
        String s = "geeks";
        ArrayList<ArrayList<String>> partitions = new
                                           ArrayList<>();
        partition(s, partitions);
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python3 program to print all palindromic
# partitions of a given string.
def checkPalindrome(string):
     
    # Returns true if str is palindrome,
    # else false
    length = len(string)
    length -= 1
    for i in range(length):
        if string[i] != string[length]:
            return False
        length -= 1
    return True
 
def printSolution(partitions):
    for i in range(len(partitions)):
        for j in range(len(partitions[i])):
            print(partitions[i][j], end = " ")
        print()
 
def addStrings(v, s, temp, index):
     
    # Goes through all indexes and
    # recursively add remaining partitions
    # if current string is palindrome.
    length = len(s)
    string = ""
 
    current = temp[:]
 
    if index == 0:
        temp = []
    for i in range(index, length):
        string += s[i]
        if checkPalindrome(string):
            temp.append(string)
            if i + 1 < length:
                addStrings(v, s, temp[:], i + 1)
            else:
                v.append(temp)
            temp = current
 
def partition(s, v):
     
    # Generates all palindromic partitions
    # of 's' and stores the result in 'v'.
    temp = []
    addStrings(v, s, temp[:], 0)
    printSolution(v)
 
# Driver Code
if __name__ == "__main__":
    s = "geeks"
    partitions = []
    partition(s, partitions)
 
# This code is contributed by
# vibhu4agarwal


C#




// C# program to print all palindromic partitions
// of a given string.
using System;
using System.Collections.Generic;
 
class GFG
{    
    // Returns true if str is palindrome, else false
    static bool checkPalindrome(String str)
    {
        int len = str.Length;
        len--;
        for (int i = 0; i < len; i++)
        {
            if (str[i] != str[len])
                return false;
            len--;
        }
        return true;
    }
     
    // Prints the partition list
    static void printSolution(List<List<String>>
                                        partitions)
    {
        foreach(List<String> i in partitions)
        {
            foreach(String j in i)
            {
                Console.Write(j+" ");
            }
            Console.WriteLine();
        }
    }
     
    // Goes through all indexes and recursively add remaining
    // partitions if current string is palindrome.
    static List<List<String>> addStrings(List<
    List<String>> v, String s, List<String> temp,
                                            int index)
    {
        int len = s.Length;
        String str = "";
        List<String> current = new List<String>(temp);
         
        if (index == 0)
            temp.Clear();
         
        // Iterate over the string
        for (int i = index; i < len; ++i)
        {
            str = str + s[i];
             
            // check whether the substring is
            // palindromic or not
            if (checkPalindrome(str))
            {
                // if palindrome add it to temp list
                temp.Add(str);
                 
                if (i + 1 < len)
                {
                    // recur to get all the palindromic
                    // partitions for the substrings
                    v = addStrings(v,s,temp,i+1);
                }
                else
                {
                    // if end of the string is reached
                    // add temp to v
                    v.Add(temp);
                }
                 
                // temp is reinitialize with the
                // current i.
                temp = new List<String>(current);
            }
        }
        return v;
    }
     
    // Generates all palindromic partitions of 's' and
    // stores the result in 'v'.
    static void partition(String s, List<List<
                                        String>> v)
    {
        // temporary List to store each
        // palindromic string
        List<String> temp = new List<String>();
         
        // calling addString method it adds all
        // the palindromic partitions to v
        v = addStrings(v, s, temp, 0);
         
        // printing the solution
        printSolution(v);
    }
     
    // Driver code
    public static void Main(String []args)
    {
        String s = "geeks";
        List<List<String>> partitions = new
                                        List<List<String>>();
        partition(s, partitions);
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// JavaScript program to print all palindromic partitions
// of a given string.
 
// Returns true if str is palindrome, else false
function checkPalindrome(str)
{
    let len = str.length;
    len--;
    for (let i=0; i<len; i++)
    {
        if (str[i] != str[len])
            return false;
        len--;
    }
    return true;
}
 
function printSolution(partitions)
{
    for (let i = 0; i < partitions.length; ++i)
    {
        for(let j = 0; j < partitions[i].length; ++j)
            document.write(partitions[i][j]," ");
        document.write("</br>");
    }
    return;
}
 
// Goes through all indexes and recursively add remaining
// partitions if current string is palindrome.
function addStrings(v,s,temp,index)
{
    let len = s.length;
    let str = "";
    let current = temp.slice();
    if (index == 0)
        temp = [];
    for (let i = index; i < len; ++i)
    {
        str = str + s[i];
        if (checkPalindrome(str))
        {
            temp.push(str);
            if (i+1 < len)
                addStrings(v,s,temp,i+1);
            else
                v.push(temp);
            temp = current;
        }
    }
    return;
}
 
// Generates all palindromic partitions of 's' and
// stores the result in 'v'.
function partition(s,v)
{
    let temp = [];
    addStrings(v, s, temp, 0);
    printSolution(v);
}
 
// Driver code
 
let s = "geeks";
let partitions = [];
partition(s, partitions);
 
// This code is contributed by shinjanpatra
 
</script>


Output

g e e k s 
g ee k s 

complexity analysis :

The time complexity of the program is O(n * 2^n), where n is the length of the input string. This is because there are 2^n-1 possible substrings of the input string, and for each substring, we check whether it is a palindrome or not, which takes O(n) time.

The space complexity of the program is also O(n * 2^n), as the number of palindromic partitions can be as high as 2^n-1, and each partition can have up to n characters. Therefore, the total space required is O(n * 2^n). 

Related Article: Dynamic Programming | Set 17 (Palindrome Partitioning) 

This article is contributed by Anshul Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

C++




// C++ program to print all palindromic partitions
// of a given string.
#include <bits/stdc++.h>
using namespace std;
 
// Returns true if str is palindrome, else false
bool checkPalindrome(string str)
{
    int len = str.length();
    len--;
    for (int i=0; i<len; i++)
    {
        if (str[i] != str[len])
            return false;
        len--;
    }
    return true;
}
 
void printSolution(vector<vector<string> > partitions)
{
    for (int i = 0; i < partitions.size(); ++i)
    {
        for(int j = 0; j < partitions[i].size(); ++j)
            cout << partitions[i][j] << " ";
        cout << endl;
    }
    return;
}
 
// Goes through all indexes and recursively add remaining
// partitions if current string is palindrome.
void addStrings(vector<vector<string> > &v, string &s,
                vector<string> &temp, int index)
{
    int len = s.length();
    string str;
    vector<string> current = temp;
    if (index == 0)
        temp.clear();
    for (int i = index; i < len; ++i)
    {
        str = str + s[i];
        if (checkPalindrome(str))
        {
            temp.push_back(str);
            if (i+1 < len)
                addStrings(v,s,temp,i+1);
            else
                v.push_back(temp);
            temp = current;
        }
    }
    return;
}
 
// Generates all palindromic partitions of 's' and
// stores the result in 'v'.
void partition(string s, vector<vector<string> >&v)
{
    vector<string> temp;
    addStrings(v, s, temp, 0);
    printSolution(v);
    return;
}
 
// Driver code
int main()
{
    string s = "geeks";
    vector<vector<string> > partitions;
    partition(s, partitions);
    return 0;
}


Java




// Java program to print all palindromic partitions
// of a given string.
import java.util.ArrayList;
public class GFG
{    
    // Returns true if str is palindrome, else false
    static boolean checkPalindrome(String str)
    {
        int len = str.length();
        len--;
        for (int i=0; i<len; i++)
        {
            if (str.charAt(i) != str.charAt(len))
                return false;
            len--;
        }
        return true;
    }
     
    // Prints the partition list
    static void printSolution(ArrayList<ArrayList<String>>
                                          partitions)
    {
        for(ArrayList<String> i: partitions)
        {
            for(String j: i)
            {
                System.out.print(j+" ");
            }
            System.out.println();
        }
    }
      
    // Goes through all indexes and recursively add remaining
    // partitions if current string is palindrome.
    static ArrayList<ArrayList<String>> addStrings(ArrayList<
       ArrayList<String>> v, String s, ArrayList<String> temp,
                                             int index)
    {
        int len = s.length();
        String str = "";
        ArrayList<String> current = new ArrayList<>(temp);
         
        if (index == 0)
            temp.clear();
         
        // Iterate over the string
        for (int i = index; i < len; ++i)
        {
            str = str + s.charAt(i);
             
            // check whether the substring is
            // palindromic or not
            if (checkPalindrome(str))
            {
                // if palindrome add it to temp list
                temp.add(str);
                 
                if (i + 1 < len)
                {   
                    // recur to get all the palindromic
                    // partitions for the substrings
                    v = addStrings(v,s,temp,i+1);
                }
                else
                {
                    // if end of the string is reached
                    // add temp to v
                    v.add(temp);
                }
                 
                // temp is reinitialize with the
                // current i.
                temp = new ArrayList<>(current);
            }
        }
        return v;
    }
      
    // Generates all palindromic partitions of 's' and
    // stores the result in 'v'.
    static void partition(String s, ArrayList<ArrayList<
                                          String>> v)
    {
        // temporary ArrayList to store each
        // palindromic string
        ArrayList<String> temp = new ArrayList<>();
         
        // calling addString method it adds all 
        // the palindromic partitions to v
        v = addStrings(v, s, temp, 0);
         
        // printing the solution
        printSolution(v);
    }
      
    // Driver code
    public static void main(String args[])
    {
        String s = "geeks";
        ArrayList<ArrayList<String>> partitions = new
                                           ArrayList<>();
        partition(s, partitions);
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python3 program to print all palindromic
# partitions of a given string.
def checkPalindrome(string):
     
    # Returns true if str is palindrome,
    # else false
    length = len(string)
    length -= 1
    for i in range(length):
        if string[i] != string[length]:
            return False
        length -= 1
    return True
 
def printSolution(partitions):
    for i in range(len(partitions)):
        for j in range(len(partitions[i])):
            print(partitions[i][j], end = " ")
        print()
 
def addStrings(v, s, temp, index):
     
    # Goes through all indexes and
    # recursively add remaining partitions
    # if current string is palindrome.
    length = len(s)
    string = ""
 
    current = temp[:]
 
    if index == 0:
        temp = []
    for i in range(index, length):
        string += s[i]
        if checkPalindrome(string):
            temp.append(string)
            if i + 1 < length:
                addStrings(v, s, temp[:], i + 1)
            else:
                v.append(temp)
            temp = current
 
def partition(s, v):
     
    # Generates all palindromic partitions
    # of 's' and stores the result in 'v'.
    temp = []
    addStrings(v, s, temp[:], 0)
    printSolution(v)
 
# Driver Code
if __name__ == "__main__":
    s = "geeks"
    partitions = []
    partition(s, partitions)
 
# This code is contributed by
# vibhu4agarwal


C#




// C# program to print all palindromic partitions
// of a given string.
using System;
using System.Collections.Generic;
 
class GFG
{    
    // Returns true if str is palindrome, else false
    static bool checkPalindrome(String str)
    {
        int len = str.Length;
        len--;
        for (int i = 0; i < len; i++)
        {
            if (str[i] != str[len])
                return false;
            len--;
        }
        return true;
    }
     
    // Prints the partition list
    static void printSolution(List<List<String>>
                                        partitions)
    {
        foreach(List<String> i in partitions)
        {
            foreach(String j in i)
            {
                Console.Write(j+" ");
            }
            Console.WriteLine();
        }
    }
     
    // Goes through all indexes and recursively add remaining
    // partitions if current string is palindrome.
    static List<List<String>> addStrings(List<
    List<String>> v, String s, List<String> temp,
                                            int index)
    {
        int len = s.Length;
        String str = "";
        List<String> current = new List<String>(temp);
         
        if (index == 0)
            temp.Clear();
         
        // Iterate over the string
        for (int i = index; i < len; ++i)
        {
            str = str + s[i];
             
            // check whether the substring is
            // palindromic or not
            if (checkPalindrome(str))
            {
                // if palindrome add it to temp list
                temp.Add(str);
                 
                if (i + 1 < len)
                {
                    // recur to get all the palindromic
                    // partitions for the substrings
                    v = addStrings(v,s,temp,i+1);
                }
                else
                {
                    // if end of the string is reached
                    // add temp to v
                    v.Add(temp);
                }
                 
                // temp is reinitialize with the
                // current i.
                temp = new List<String>(current);
            }
        }
        return v;
    }
     
    // Generates all palindromic partitions of 's' and
    // stores the result in 'v'.
    static void partition(String s, List<List<
                                        String>> v)
    {
        // temporary List to store each
        // palindromic string
        List<String> temp = new List<String>();
         
        // calling addString method it adds all
        // the palindromic partitions to v
        v = addStrings(v, s, temp, 0);
         
        // printing the solution
        printSolution(v);
    }
     
    // Driver code
    public static void Main(String []args)
    {
        String s = "geeks";
        List<List<String>> partitions = new
                                        List<List<String>>();
        partition(s, partitions);
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// JavaScript program to print all palindromic partitions
// of a given string.
 
// Returns true if str is palindrome, else false
function checkPalindrome(str)
{
    let len = str.length;
    len--;
    for (let i=0; i<len; i++)
    {
        if (str[i] != str[len])
            return false;
        len--;
    }
    return true;
}
 
function printSolution(partitions)
{
    for (let i = 0; i < partitions.length; ++i)
    {
        for(let j = 0; j < partitions[i].length; ++j)
            document.write(partitions[i][j]," ");
        document.write("</br>");
    }
    return;
}
 
// Goes through all indexes and recursively add remaining
// partitions if current string is palindrome.
function addStrings(v,s,temp,index)
{
    let len = s.length;
    let str = "";
    let current = temp.slice();
    if (index == 0)
        temp = [];
    for (let i = index; i < len; ++i)
    {
        str = str + s[i];
        if (checkPalindrome(str))
        {
            temp.push(str);
            if (i+1 < len)
                addStrings(v,s,temp,i+1);
            else
                v.push(temp);
            temp = current;
        }
    }
    return;
}
 
// Generates all palindromic partitions of 's' and
// stores the result in 'v'.
function partition(s,v)
{
    let temp = [];
    addStrings(v, s, temp, 0);
    printSolution(v);
}
 
// Driver code
 
let s = "geeks";
let partitions = [];
partition(s, partitions);
 
// This code is contributed by shinjanpatra
 
</script>


Output

g e e k s 
g ee k s 

The time and space complexity of the given program to print all palindromic partitions of a given string are:

Time Complexity:

The checkPalindrome() function checks if a given string is a palindrome, which takes O(n) time, where n is the length of the string.
The addStrings() function goes through all indexes of the string and recursively adds remaining partitions if the current string is a palindrome. In the worst case, the function will have to go through all substrings, which takes O(n^2) time.
The partition() function calls the addStrings() function, which takes O(n^2) time in the worst case.
Therefore, the overall time complexity of the program is O(n^2).

Space Complexity:

The program uses a vector of vectors to store all the palindromic partitions of a given string. The maximum number of partitions for a given string of length n can be (2^(n-1)), which is the total number of ways to place the partition bars between the characters of the string. Therefore, the space complexity of the program is O(2^(n-1)).
Note: In practice, the space complexity can be lower than O(2^(n-1)) since not all partitions may be palindromic. However, in the worst case, the space complexity is O(2^(n-1)).


My Personal Notes arrow_drop_up
Last Updated : 30 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials