Print all palindromic partitions of a string in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a palindromic string. And we have to print all the partitions of this string. In this problem, we will find all possible palindrome partitions of the string by cutting it.

Let’s take an example to understand the problem -

Input − string = ‘ababa’
Output − ababa , a bab a, a b a b a ….

The solution, to this problem, is to check if a substring is a palindrome or not. And print the substring if it is substring.


The below program will illustrate the solution −

 Live Demo

using namespace std;
bool isPalindrome(string str, int low, int high){
   while (low < high) {
      if (str[low] != str[high])
         return false;
   return true;
void palindromePartition(vector<vector<string> >&allPart, vector<string> &currPart, int start, int n, string str){
   if (start >= n) {
   for (int i=start; i<n; i++){
      if (isPalindrome(str, start, i)) {
         currPart.push_back(str.substr(start, i-start+1));
         palindromePartition(allPart, currPart, i+1, n, str);
void generatePalindromePartitions(string str){
   int n = str.length();
   vector<vector<string> > partitions;
   vector<string> currPart;
   palindromePartition(partitions, currPart, 0, n, str);
   for (int i=0; i< partitions.size(); i++ ) {
      for (int j=0; j<partitions[i].size(); j++)
      cout<<partitions[i][j]<<" ";
int main() {
   string str = "abaaba";
   cout<<"Palindromic partitions are :\n";
   return 0;


Palindromic partitions are :
a b a a b a
a b a aba
a b aa b a
a baab a
aba a b a
aba aba
Published on 16-Jan-2020 17:27:24