The Wayback Machine - https://web.archive.org/web/20240905164447/https://www.geeksforgeeks.org/given-a-string-print-all-possible-palindromic-partition/
Open In App

Print all Palindromic Partitions of a String using Backtracking

Last Updated : 27 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
61.47%
18.5K

Given a string, find all possible palindromic partitions of given string.

Note that this problem is different from Palindrome Partitioning Problem, there the task was to find the partitioning with minimum cuts in input string. Here we need to print all possible partitions.

Example: 

Input: nitin
Output: n i t i n
n iti n
nitin

Input: geeks
Output: g e e k s
g ee k s

Brute Force Approach:

The idea is to use recursion and backtracking.

  • Partition the string to generate the substrings.
  • Check whether the substring generated is palindrome or not.
  • If the substring generated is palindrome,
    • then add this substring to our current list and recursively call the function for the remaining string.
  • When the end of the string is reached the current list is added to the result.

Below is the implementation of above approach.

C++
#include <bits/stdc++.h>
using namespace std;

class GFG {

public:
    // Check whether the string is palindrom or not.
    bool checkPalindrome(string& s)
    {
        int n = s.size();
        int i = 0, j = n - 1;
        while (i < j) {
            if (s[i] != s[j])
                return false;
            i++;
            j--;
        }
        return true;
    }
    // Recursive function which takes starting index idx
    // and generates all substrings starting at idx.
    // If substring generated is palindrome it adds to
    // current list and makes a recursive call for
    // remaining  string.
    void Partition(vector<vector<string> >& res, string& s,
                   int idx, vector<string>& curr)
    {
        // If we reach the end of string at the current list
        // to the result.
        if (idx == s.size()) {
            res.push_back(curr);
            return;
        }
        // Stores the current substring.
        string t;
        for (int i = idx; i < s.size(); i++) {
            t.push_back(s[i]);

            // Check whether the string is palindrome is
            // not.
            if (checkPalindrome(t)) {

                // Adds the string to current list
                curr.push_back(t);

                // Recursive call for the remaining string
                Partition(res, s, i + 1, curr);

                // Remove the string from the current
                // string.
                curr.pop_back();
            }
        }
    }
};
// Driver code
int main()
{
    GFG ob;
    // Stores all the partition
    vector<vector<string> > res;
    string s = "geeks";

    // Starting index of string
    int idx = 0;

    // Current list
    vector<string> curr;
    ob.Partition(res, s, idx, curr);
    for (auto& v : res) {
        for (auto& it : v) {
            cout << it << " ";
        }
        cout << "\n";
    }
    return 0;
}
Java
/*package whatever //do not write package name here */

import java.io.*;
import java.util.ArrayList;

class GFG {

    //funtion to check whether partitioned string is palindrome or not
    public boolean checkPalindrome(String s) {
        int n = s.length();
        int i = 0;
        int j = n-1;
        while(i < j) {
            if(s.charAt(i) != s.charAt(j))
                return false;

            i++;
            j--;
        }
        return true;
    }

    // Recursive funtion which takes index ind and generates all substrings starting at ind.
    // if substring generated is palindrome it adds to current list and makes a recursive call for remaining string

    public void partition(ArrayList<ArrayList<String>> res, String s, int ind, ArrayList<String> curr) {
        // if we reach the end of string
        // add the current list to the result

        if(ind == s.length()) {
            res.add(new ArrayList<String>(curr));
            return;
        }

        // Store the current substring
        String temp = "";

        for(int i = ind; i < s.length(); i++) {
            temp += s.charAt(i);

            // check if string temp is palindrome or not
            if(checkPalindrome(temp)){

                // adds the string to current list
                curr.add(temp);

                // Recursive call for the remaining string
                partition(res, s, i+1, curr);

                // Remove the string from the current list - (backtracking)
                curr.remove(curr.size()-1);
            }
        }
        
    }
    public static void main(String[] args) {

        // creating obj of GFG class
        GFG obj = new GFG();

        // Stores all partitions generated at the end
        ArrayList<ArrayList<String>> res = new ArrayList<>();
        
        String s = "geeks";

        int ind = 0;

        // Store the partition at current iteration
        ArrayList<String> curr = new ArrayList<>();

        // calling funtion to get partition
        obj.partition(res, s, ind, curr);

        for(ArrayList<String> iter : res) {
            System.out.println(iter);
        }
    }
}
Python
# Python implementation
class GFG:

    def checkPalindrome(self, s):
        n = len(s)
        i, j = 0, n - 1
        while i < j:
            if s[i] != s[j]:
                return False
            i += 1
            j -= 1
        return True

    def partition(self, res, s, ind, curr):
        if ind == len(s):
            res.append(list(curr))
            return

        temp = ""
        for i in range(ind, len(s)):
            temp += s[i]
            if self.checkPalindrome(temp):
                curr.append(temp)
                self.partition(res, s, i + 1, curr)
                curr.pop()

    def main(self):
        obj = GFG()
        res = []
        s = "geeks"
        ind = 0
        curr = []
        obj.partition(res, s, ind, curr)

        for iter in res:
            print(iter)

# Creating an instance of GFG class
gfg_obj = GFG()
gfg_obj.main()
C#
using System;
using System.Collections.Generic;

class GFG {
    public bool CheckPalindrome(string s)
    {
        int n = s.Length;
        int i = 0, j = n - 1;

        // Check whether the string is a palindrome
        while (i < j) {
            if (s[i] != s[j])
                return false;
            i++;
            j--;
        }
        return true;
    }

    public void Partition(List<List<string> > res, string s,
                          int idx, List<string> curr)
    {
        // If we reach the end of the string, add the
        // current list to the result.
        if (idx == s.Length) {
            res.Add(new List<string>(curr));
            return;
        }

        // Stores the current substring.
        string t = "";
        for (int i = idx; i < s.Length; i++) {
            t += s[i];

            // Check whether the string is a palindrome.
            if (CheckPalindrome(t)) {
                // Add the string to the current list.
                curr.Add(t);

                // Recursive call for the remaining string.
                Partition(res, s, i + 1, curr);

                // Remove the string from the current list.
                curr.RemoveAt(curr.Count - 1);
            }
        }
    }

    public static void Main(string[] args)
    {
        GFG ob = new GFG();

        // Stores all the partitions
        List<List<string> > res = new List<List<string> >();
        string s = "geeks";

        // Starting index of the string
        int idx = 0;

        // Current list
        List<string> curr = new List<string>();

        ob.Partition(res, s, idx, curr);

        foreach(var v in res)
        {
            foreach(var it in v)
            {
                Console.Write(it + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
class GFG {
    // Check whether the string is a palindrome or not.
    checkPalindrome(s) {
        let n = s.length;
        let i = 0, j = n - 1;
        while (i < j) {
            if (s[i] !== s[j]) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }

    // Recursive function which takes starting index idx
    // and generates all substrings starting at idx.
    // If the substring generated is a palindrome, it adds it
    // to the current list and makes a recursive call for the
    // remaining string.
    partition(res, s, idx, curr) {
        // If we reach the end of the string, add the current list to the result.
        if (idx === s.length) {
            res.push([...curr]);
            return;
        }
        // Stores the current substring.
        let t = '';
        for (let i = idx; i < s.length; i++) {
            t += s[i];

            // Check whether the string is a palindrome or not.
            if (this.checkPalindrome(t)) {
                // Add the string to the current list.
                curr.push(t);

                // Recursive call for the remaining string.
                this.partition(res, s, i + 1, curr);

                // Remove the string from the current list.
                curr.pop();
            }
        }
    }
}

// Driver code
function main() {
    const ob = new GFG();
    // Stores all the partitions.
    const res = [];
    const s = "geeks";

    // Starting index of the string.
    let idx = 0;

    // Current list.
    const curr = [];
    ob.partition(res, s, idx, curr);

    // Print the result.
    for (let v of res) {
        console.log(v.join(' '));
    }
}

main();

Output
g e e k s 
g ee k s 

Time complexity: O(n*2n), where n is the size of the string. There are 2n possibilities of partitioning the string of length n, and for each possibility, we are checking if the string is a palindrome that costs O(n) time. Hence the overall time complexity is O(n*2n).
Auxiliary Space: O(2n), to store all possible partition of string.

Also read about the Bit Manipulation approach or this problem.



Similar Reads

Print all Palindromic Partitions of a String using Bit Manipulation
Given a string, find all possible palindromic partitions of a given string. Note that this problem is different from Palindrome Partitioning Problem, there the task was to find the partitioning with minimum cuts in input string. Here we need to print all possible partitions. Example: Input: nitinOutput: n i t i n n iti n nitin Input: geeksOutput: g
10 min read
Count of Valid Partitions such that all Partitions lie in Range [1, L]
Given a string S containing only digits and an integer L, find the number of ways to partition the given string such that each partition forms a number that lies between the range [1, L]. Since the answer may be very large, return the answer modulo 109+7. Examples: Input: S = "1000", L = 10000Output: 1Explanation: The only possible partition is [10
8 min read
Minimum cuts required to convert a palindromic string to a different palindromic string
Given palindromic string s, the task is to find minimum k, such that you can cut this string into k+1 parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string s. If it is impossible then print -1.Examples: Input : string = "civic" Output : 2 Explanation : ci | v | ic --&gt; ic |
15+ min read
Make palindromic string non-palindromic by rearranging its letters
Given string str containing lowercase alphabets (a - z). The task is to print the string after rearranging some characters such that the string becomes non-palindromic. If it's impossible to make the string non-palindrome then print -1. Examples: Input: str = "abba" Output: aabb Input: str = "zzz" Output: -1 Brute Force: Iterate through all possibl
9 min read
Print all possible palindromic string formed using any pair of given strings
Given an array of strings arr[] containing N words, the task is to print all possible palindromic string by combining any two strings from the given array. Examples: Input: arr[] = ["geekf", "geeks", "or", "keeg", "abc", "ba"]Output: ["geekfkeeg", "geekskeeg", "abcba"] Explanation:Below pairs forms the palindromic string on combining:1. "geekf" + "
12 min read
Longest Palindromic Substring using Palindromic Tree | Set 3
Given a string, find the longest substring which is a palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”. Prerequisite : Palindromic Tree | Longest Palindromic Substring Structure of Palindromic Tree : The palindromic Tree’s actual structure is close to the directed graph. It is actually a merged s
15+ min read
Lengths of maximized partitions of a string such that each character of the string appears in one substring
Given string str of lowercase alphabets, split the given string into as many substrings as possible such that each character from the given string appears in a single substring. The task is to print the length of all such partitions. Examples: Input: str = "acbbcc"Output: 1 5Explanation:Possible partitions where each character of the strings occurs
8 min read
Maximized partitions of a string such that each character of the string appears in one substring
Given a string S, split the given string into as many substrings as possible such that each character from the given string appears in a single substring and print all these possible parts. The task is to print those substrings. Examples: Input: S = "ababcbacadefegdehijhklij" Output: ababcbaca defegde hijhklij Explanation: a, b, c are only present
8 min read
Minimize partitions in given string to get another string
Given two strings A and B, print the minimum number of slices required in A to get another string B. In case, if it is not possible to get B from A, then print "-1". Examples : Input: A = "geeksforgeeks", B = "ksgek"Output: 5Explanation: g | ee | ks | forge | ek | s : minimum 5 slices are required to create B Input: A = "topgames", B = "mepo"Output
15+ min read
Print all the palindromic permutations of given string in alphabetic order
Given a string str of size n. The problem is to print all the palindromic permutations of str in alphabetic order if possible else print "-1". Examples : Input : str = "aabb" Output : abba baab Input : malayalam Output : aalmymlaa aamlylmaa alamymala almayamla amalylama amlayalma laamymaal lamayamal lmaayaaml maalylaam malayalam mlaayaalm Prerequis
15+ min read
Print the DFS traversal step-wise (Backtracking also)
Given a graph, the task is to print the DFS traversal of a graph which includes every step including the backtracking. 1st step:- 0 -&gt; 1 2nd step:- 1 -&gt; 5 3rd step:- 5 -&gt; 1 (backtracking step) 4th step:- 1 -&gt; 6... and so on till all the nodes are visited. Dfs step-wise(including backtracking) is: 0 1 5 1 6 7 8 7 6 1 0 2 4 2 9 3 10 Note:
10 min read
Generate all distinct subsequences of array using backtracking
Given an array arr[] consisting of N positive integers, the task is to generate all distinct subsequences of the array. Examples: Input: arr[] = {1, 2, 2}Output: {} {1} {1, 2} {1, 2, 2} {2} {2, 2}Explanation:The total subsequences of the given array are {}, {1}, {2}, {2}, {1, 2}, {1, 2}, {2, 2}, {1, 2, 2}.Since {2} and {1, 2} are repeated twice, pr
7 min read
Sum of elements of all partitions of number such that no element is less than K
Given an integer N, the task is to find an aggregate sum of all integer partitions of this number such that each partition does not contain any integer less than K. Examples: Input: N = 6 and K = 2 Output: 24 In this case, there are 4 valid partitions. 1) {6} 2) {4, 2} 3) {3, 3} 4) {2, 2, 2} Therefore, aggregate sum would be 6 + 4 + 2 + 3 + 3 + 2 +
9 min read
Generate all unique partitions of an integer | Set 2
Given a positive integer n, the task is to generate all possible unique ways to represent n as sum of positive integers.Examples: Input: 4 Output: 4 3 1 2 2 2 1 1 1 1 1 1Input: 3 Output: 3 2 1 1 1 1 Approach: We have already discussed the implementation of generating unique partitions in this post. This post contains another and far more intuitive
8 min read
Partitions possible such that the minimum element divides all the other elements of the partition
Given an integer array arr[], the task is to count the number of partitions possible such that in each partition the minimum element divides all the other elements of the partition. The partition need not be continuous.Examples: Input: arr[] = {10, 7, 20, 21, 13} Output: 3 The possible partitions are {10, 20}, {7, 21} and {13}. In each partition, a
6 min read
Generate all unique partitions of an integer
Given a positive integer n, generate all possible unique ways to represent n as sum of positive integers. Examples: Input: n = 2 Output: 2 1 1 Input: n = 3 Output: 3 2 1 1 1 1 Note: 2+1 and 1+2 are considered as duplicates. Input: n = 4 Output: 4 3 1 2 2 2 1 1 1 1 1 1 Recommended ProblemUnique partitionsSolve Problem Solution: We print all partitio
15+ min read
Maximum Balanced String Partitions
Given a balanced string str of size N with an equal number of L and R, the task is to find a maximum number X, such that a given string can be partitioned into X balanced substring. A string called to be balanced if the number of 'L's in the string equals the number of 'R's. Examples: Input : str = "LRLLRRLRRL" Output : 4 Explanation: { "LR", "LLRR
7 min read
Maximize partitions in given Binary String having same ratio of 0s and 1s
Given a binary string S of size N, the task is to find the maximum number of partitions of string S such that the ratio of the number of 0 and 1 in all the partitions are the same. Examples: Input: S = "010100001"Output: 3Explanation: The substring [0, 2], [3, 5] and [6, 8] have the same ratio of '0' and '1' is 2:1. Therefore, the maximum possible
9 min read
Minimum partitions of String such that each part is at most K
Given a string S of size N consisting of numerical digits 1-9 and a positive integer K, the task is to minimize the partitions of the string such that each part is at most K. If it’s impossible to partition the string print -1. Examples: Input: S = "3456", K = 45Output: 2Explanation: One possible way is to partition as 3, 45, 6. Another possibility
8 min read
Print all Palindromic Levels Of a Binary Tree
Given a Binary Tree, the task is to print all palindromic levels of this tree. Palindrome Level Any level of a Binary tree is said to be a palindromic level if on traversing it from left to right, the result is same as traversing that level from right to left. Examples: Input: 1 / \ 12 13 / / \ 11 6 11 \ / 2 2 Output: 1 11 6 11 2 2 Explanation: Fir
11 min read
Print all palindromic paths from top left to bottom right in a matrix
Given a m*n matrix mat[][] containing only lowercase alphabetical characters, the task is to print all palindromic paths from the top-left cell to the bottom-right cell. A path is defined as a sequence of cells starting from the top-left and ending at the bottom-right, and we can only move right or down from any cell. Example: Input: mat = [['a', '
7 min read
Print the longest palindromic prefix of a given string
Given a string str, the task is to find the longest palindromic prefix of the given string. Examples: Input: str = "abaac" Output: aba Explanation: The longest prefix of the given string which is palindromic is "aba". Input: str = "abacabaxyz" Output: abacaba Explanation: The prefixes of the given string which is palindromic are "aba" and "abacabax
12 min read
Print the last character of lexicographically smallest non-palindromic permutation of a string
Given string str, the task is to print the last character of the lexicographically smallest non-palindromic permutation of the given string. If no such permutation exists, print "-1". Examples: Input: str = "deepqvu"Output: vExplanation: The string "deepquv" is the lexicographically smallest permutation which is not a palindrome.Therefore, the last
13 min read
Rat in a Maze | Backtracking using Stack
Prerequisites - Recursion, Backtracking and Stack Data Structure. A Maze is given as N*M binary matrix of blocks and there is a rat initially at (0, 0) ie. maze[0][0] and the rat wants to eat food which is present at some given block in the maze (fx, fy). In a maze matrix, 0 means that the block is a dead end and 1 means that the block can be used
15+ min read
Travelling Salesman Problem implementation using BackTracking
Travelling Salesman Problem (TSP): Given a set of cities and distance between every pair of cities, the problem is to find the shortest possible route that visits every city exactly once and returns back to the starting point.Note the difference between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there exist a tour that v
9 min read
Maximum size subset with given sum using Backtracking
Given an array arr[] consisting of N integers and an integer K, the task is to find the length of the longest subsequence with a sum equal to K.Examples: Input: arr[] = {-4, -2, -2, -1, 6}, K = 0 Output: 3 Explanation: The longest subsequence is of length 3 which is {-4, -2, 6} having sum 0.Input: arr[] = {-3, 0, 1, 1, 2}, K = 1 Output: 5 Explanati
9 min read
Subset Sum Problem using Backtracking
Given a set[] of non-negative integers and a value sum, the task is to print the subset of the given set whose sum is equal to the given sum. Examples:  Input: set[] = {1,2,1}, sum = 3Output: [1,2],[2,1]Explanation: There are subsets [1,2],[2,1] with sum 3. Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 30Output: []Explanation: There is no subset that
8 min read
Word Break Problem using Backtracking
Given a valid sentence without any spaces between the words and a dictionary of valid English words, find all possible ways to break the sentence into individual dictionary words. Example: Consider the following dictionary { i, like, sam, sung, samsung, mobile, ice, and, cream, icecream, man, go, mango} Input: "ilikesamsungmobile" Output: i like sa
8 min read
Minimum partitions of maximum size 2 and sum limited by given value
Given an array arr[] of positive numbers, find minimum number of sets in array which satisfy following property, A set can contain maximum two elements in it. The two elements need not to be contiguous. Sum of elements of set should be less than or equal to given Key. It may be assumed that given key is greater than or equal to the largest array el
6 min read
Find partitions to maximize even and odd count sum in left and right part
Given an array arr[] having N positive integers, the task is to find all the indices i (1 ≤ i ≤ N - 1) such that, the sum of the count of even numbers in the left subarray [0, i - 1] and the count of odd numbers in the right subarray [i, n - 1] is the maximum among all i's. Example: Input: arr[] = {1, 3, 4, 5, 6}Output: 1 3Explanation: Count of eve
15+ min read
Article Tags :
Practice Tags :