The Wayback Machine - https://web.archive.org/web/20240905164447/https://www.geeksforgeeks.org/print-palindromic-partitions-string/
Open In App

Print all Palindromic Partitions of a String using Bit Manipulation

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

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: nitin
Output: n i t i n
n iti n
nitin

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

Please refer Print all Palindromic Partitions of a String using Backtracking for Backtracking approach for this problem.

Print all Palindromic Partitions Using Bit Manipulation

The idea is to consider the space between two characters in the string.

  • If there n characters in the string, then there are n-1 positions to put a space or say cut the string.
  • Each of these positions can be given a binary number 1 (If a cut is made in this position) or 0 (If no cut is made in this position).
  • This will give a total of 2n-1 partitions and for each partition check whether this partition is palindrome or not.

Illustration:

Input : geeks

0100 => ["ge","eks"] (not valid)
1011 => ["g","ee","k","s"] (valid)
1111 => ["g","e","e","k","s"] (valid)
0000 => ["geeks"] (not valid)

Below is the implementation of the idea.

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

class GFG {
public:
    vector<vector<string> > ans;

    // Checks whether a Partition of string is palindrome or
    // not.
    bool checkPalindrome(vector<string> currPartition)
    {
        for (auto s : currPartition) {
            int n = s.size();
            int i = 0, j = n - 1;
            while (i < j) {
                if (s[i] != s[j])
                    return false;
                i++;
                j--;
            }
        }
        return true;
    }

    // Generates partition of a string according to
    // bitString.
    void generatePartition(string& s, string& bitString)
    {
        vector<string> currPartition;
        string subString;
        subString.push_back(s[0]);
        for (int i = 0; i < bitString.size(); i++) {

            // If current character of bitString is '0' no
            // cut will be made and next character will be
            // included in the current subString
            if (bitString[i] == '0') {
                // no cut is made so next character is added
                // to substring
                subString.push_back(s[i + 1]);
            }

            // If current character of bitString is '1' then
            // a cut will be made and current subString will
            // be appended in current Partition and new
            // subString will start from next position.
            else {
                // subString is added to current Partition.
                currPartition.push_back(subString);

                subString.clear();

                // New substring is created starting from
                // next position of string s.
                subString.push_back(s[i + 1]);
            }
        }
        currPartition.push_back(subString);
        if (checkPalindrome(currPartition)) {
            ans.push_back(currPartition);
        }
    }

    // Recursive function to generate all the bitStrings
    // which will denote the positions in which string will
    // be cut.
    void bitManipulation(string& s, string& bitString)
    {
        // When a bitString is generated generatePartition()
        // will be called to partition the string
        // accordingly.
        if (bitString.size() == s.size() - 1) {
            generatePartition(s, bitString);
            return;
        }
        bitString.push_back('1');
        bitManipulation(s, bitString);
        bitString.pop_back();
        bitString.push_back('0');
        bitManipulation(s, bitString);
        bitString.pop_back();
    }
    // Return all the palindromic partition of string s.
    vector<vector<string> > Partition(string s)
    {
        string bitString;
        bitManipulation(s, bitString);
        return ans;
    }
};

int main()
{
    GFG ob;
    // Stores all the partition
    vector<vector<string> > ans;
    string s = "geeks";
    ans = ob.Partition(s);
    for (auto& v : ans) {
        for (auto& it : v) {
            cout << it << " ";
        }
        cout << "\n";
    }
    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

class GFG {
    List<List<String>> ans = new ArrayList<>();

    // Checks whether a Partition of string is palindrome or not.
    boolean checkPalindrome(List<String> currPartition) {
        for (String s : currPartition) {
            int n = s.length();
            int i = 0, j = n - 1;
            while (i < j) {
                if (s.charAt(i) != s.charAt(j))
                    return false;
                i++;
                j--;
            }
        }
        return true;
    }

    // Generates partition of a string according to bitString.
    void generatePartition(String s, String bitString) {
        List<String> currPartition = new ArrayList<>();
        StringBuilder subString = new StringBuilder();
        subString.append(s.charAt(0));
        for (int i = 0; i < bitString.length(); i++) {
            // If current character of bitString is '0' no cut will be made
            // and next character will be included in the current subString
            if (bitString.charAt(i) == '0') {
                // no cut is made so next character is added to substring
                subString.append(s.charAt(i + 1));
            }
            // If current character of bitString is '1' then
            // a cut will be made and current subString will
            // be appended in current Partition and new
            // subString will start from next position.
            else {
                // subString is added to current Partition.
                currPartition.add(subString.toString());

                subString.setLength(0);

                // New substring is created starting from
                // next position of string s.
                subString.append(s.charAt(i + 1));
            }
        }
        currPartition.add(subString.toString());
        if (checkPalindrome(currPartition)) {
            ans.add(currPartition);
        }
    }

    // Recursive function to generate all the bitStrings
    // which will denote the positions in which string will
    // be cut.
    void bitManipulation(String s, String bitString) {
        // When a bitString is generated generatePartition()
        // will be called to partition the string
        // accordingly.
        if (bitString.length() == s.length() - 1) {
            generatePartition(s, bitString);
            return;
        }
        bitString += '1';
        bitManipulation(s, bitString);
        bitString = bitString.substring(0, bitString.length() - 1);
        bitString += '0';
        bitManipulation(s, bitString);
        bitString = bitString.substring(0, bitString.length() - 1);
    }

    // Return all the palindromic partition of string s.
    List<List<String>> partition(String s) {
        String bitString = "";
        bitManipulation(s, bitString);
        return ans;
    }

    public static void main(String[] args) {
        GFG ob = new GFG();
        // Stores all the partition
        List<List<String>> ans;
        String s = "geeks";
        ans = ob.partition(s);
        for (List<String> v : ans) {
            for (String it : v) {
                System.out.print(it + " ");
            }
            System.out.println();
        }
    }
}
Python
class PalindromePartition:
    def __init__(self):
        self.ans = []

    def check_palindrome(self, curr_partition):
        for s in curr_partition:
            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 generate_partition(self, s, bit_string):
        curr_partition = []
        sub_string = s[0]
        for i in range(len(bit_string)):
            # If current character of bitString is '0', no cut will be made,
            # and the next character will be included in the current subString.
            if bit_string[i] == '0':
                # No cut is made, so the next character is added to the substring.
                sub_string += s[i + 1]
            # If the current character of bitString is '1', then a cut will be made,
            # and the current subString will be appended in the current partition,
            # and a new subString will start from the next position.
            else:
                # SubString is added to the current partition.
                curr_partition.append(sub_string)

                # New substring is created starting from the next position of the string s.
                sub_string = s[i + 1]

        curr_partition.append(sub_string)
        if self.check_palindrome(curr_partition):
            self.ans.append(curr_partition)

    def bit_manipulation(self, s, bit_string):
        # When a bitString is generated, generate_partition() will be called
        # to partition the string accordingly.
        if len(bit_string) == len(s) - 1:
            self.generate_partition(s, bit_string)
            return
        bit_string += '1'
        self.bit_manipulation(s, bit_string)
        bit_string = bit_string[:-1]  # Pop the last character
        bit_string += '0'
        self.bit_manipulation(s, bit_string)

    def partition(self, s):
        bit_string = ""
        self.bit_manipulation(s, bit_string)
        return self.ans


if __name__ == "__main__":
    ob = PalindromePartition()
    s = "geeks"
    ans = ob.partition(s)
    for v in ans:
        print(" ".join(v))
C#
using System;
using System.Collections.Generic;

class GFG
{
    private List<List<string>> ans = new List<List<string>>();
    // Checks whether a Partition of 
    //string is palindrome or not.
    private bool CheckPalindrome(List<string> currPartition)
    {
        foreach (var s in currPartition)
        {
            int n = s.Length;
            int i = 0, j = n - 1;
            while (i < j)
            {
                if (s[i] != s[j])
                    return false;
                i++;
                j--;
            }
        }
        return true;
    }
    // Generates partition of a string 
  // according to bitString.
    private void GeneratePartition(string s, string bitString)
    {
        List<string> currPartition = new List<string>();
        string subString = s[0].ToString();
        for (int i = 0; i < bitString.Length; i++)
        {
            if (bitString[i] == '0')
            {
                subString += s[i + 1];
            }
            // If current character of bitString is '1', a cut will be made,
            // and the current subString will be appended in the current Partition,
            // and a new subString will start from the next position.
            else
            {
                // subString is added to current Partition.
                currPartition.Add(subString);

                subString = "";

                // New substring is created starting from the next position of string s.
                subString += s[i + 1];
            }
        }
        currPartition.Add(subString);
        if (CheckPalindrome(currPartition))
        {
            ans.Add(currPartition);
        }
    }
    // Recursive function to generate all the bitStrings
    // which will denote the positions in which string will be cut.
    private void BitManipulation(string s, string bitString)
    {
        if (bitString.Length == s.Length - 1)
        {
            GeneratePartition(s, bitString);
            return;
        }
        bitString += '1';
        BitManipulation(s, bitString);
        bitString = bitString.Remove(bitString.Length - 1);
        bitString += '0';
        BitManipulation(s, bitString);
        bitString = bitString.Remove(bitString.Length - 1);
    }
    // Return all the palindromic 
  // partitions of string s.
    public List<List<string>> Partition(string s)
    {
        string bitString = "";
        BitManipulation(s, bitString);
        return ans;
    }
}
class Geek
{
    static void Main()
    {
        GFG ob = new GFG();
        // Stores all the partitions
        List<List<string>> ans;
        string s = "geeks";
        ans = ob.Partition(s);
        foreach (var v in ans)
        {
            foreach (var it in v)
            {
                Console.Write(it + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
class GFG {
    constructor() {
        this.ans = [];
    }

    // Checks whether a Partition of string is palindrome or not.
    checkPalindrome(currPartition) {
        for (const s of currPartition) {
            const n = s.length;
            let i = 0, j = n - 1;
            while (i < j) {
                if (s.charAt(i) !== s.charAt(j))
                    return false;
                i++;
                j--;
            }
        }
        return true;
    }

    // Generates partition of a string according to bitString.
    generatePartition(s, bitString) {
        const currPartition = [];
        let subString = s.charAt(0);
        for (let i = 0; i < bitString.length; i++) {
            // If current character of bitString is '0' no cut will be made
            // and next character will be included in the current subString
            if (bitString.charAt(i) === '0') {
                // no cut is made so next character is added to substring
                subString += s.charAt(i + 1);
            }
            // If current character of bitString is '1' then
            // a cut will be made and current subString will
            // be appended in current Partition and new
            // subString will start from next position.
            else {
                // subString is added to current Partition.
                currPartition.push(subString);

                subString = '';

                // New substring is created starting from
                // next position of string s.
                subString += s.charAt(i + 1);
            }
        }
        currPartition.push(subString);
        if (this.checkPalindrome(currPartition)) {
            this.ans.push(currPartition);
        }
    }

    // Recursive function to generate all the bitStrings
    // which will denote the positions in which string will
    // be cut.
    bitManipulation(s, bitString) {
        // When a bitString is generated generatePartition()
        // will be called to partition the string
        // accordingly.
        if (bitString.length === s.length - 1) {
            this.generatePartition(s, bitString);
            return;
        }
        bitString += '1';
        this.bitManipulation(s, bitString);
        bitString = bitString.substring(0, bitString.length - 1);
        bitString += '0';
        this.bitManipulation(s, bitString);
        bitString = bitString.substring(0, bitString.length - 1);
    }

    // Return all the palindromic partition of string s.
    partition(s) {
        let bitString = '';
        this.bitManipulation(s, bitString);
        return this.ans;
    }
}

// Create an instance of the GFG class
const ob = new GFG();

// Stores all the partition
let ans;
const s = 'geeks';
ans = ob.partition(s);

// Print the results on the same line
for (const v of ans) {
    let line = '';
    for (const it of v) {
        line += it + ' ';
    }
    console.log(line);
}

Output
g e e k s 
g ee k s 

Time complexity: O(n*2n), n is size of the string.
Auxiliary Space: O(2n), to store all possible partition of string.



Previous Article
Next Article

Similar Reads

Print all Palindromic Partitions of a String using Backtracking
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: nitinOutput: n i t i n n iti n nitin Input: geeksOutput: g e
7 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
All about Bit Manipulation
Bit Manipulation is a technique used in a variety of problems to get the solution in an optimized way. This technique is very effective from a Competitive Programming point of view. It is all about Bitwise Operators which directly works upon binary numbers or bits of numbers that help the implementation fast. Below are the Bitwise Operators that ar
14 min read
Winner in the Rock-Paper-Scissor game using Bit manipulation
Two players are playing a series of games of Rock–paper–scissors. There are a total of N games played represented by an array arr[][] where arr[i][0] is the move of player one and arr[i][1] is the move of the player two in the ith game from the set {'R', 'P', 'S'}. The task is to find the winner of each of the game. Note that the game is a draw if
6 min read
Find square root of a number using Bit Manipulation
Given a non-negative integer N, the task is to find the square root of N using bitwise operations. If the integer is not the perfect square, return largest integer that is smaller than or equal to square root of N i.e., floor(√N). Examples: Input: N = 36Output: 6Explanation: The square root of 36 is 6. Input: N = 19Output: 4Explanation: The square
7 min read
Store two numbers in one Byte using Bit manipulation
Given two values A and B (A, B &lt; 16), the task is to store the numbers in one byte. Examples: Input: A = 5, B = 9Output: 89Explanation: 5 in binary form is 0101 and the binary form for 9 is 1001. Since 1 byte contains 8 bits, we can store these two nibbles in that 1 bit, forming 01011001 which when converted into decimal becomes 89. Input: A = 2
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
Maximize the Expression | Bit Manipulation
Given two positive integers A and B. Let's define D such that B AND D = D. The task is to maximize the expression A XOR D.Examples: Input: A = 11 B = 4 Output: 15 Take D = 4 as (B AND D) = (4 AND 4) = 4. Also, (A XOR D) = (11 XOR 4) = 15 which is the maximum according to the given condition. Input: A = 9 and B = 13 Output: 13 Naive approach: Since
7 min read
Maximize the expression (A AND X) * (B AND X) | Bit Manipulation
Given two positive integers A and B such that A != B, the task is to find a positive integer X which maximizes the expression (A AND X) * (B AND X).Example: Input: A = 9 B = 8 Output: 8 (9 AND 8) * (8 AND 8) = 8 * 8 = 64 (maximum possible)Input: A = 11 and B = 13 Output: 9 Naive approach: One can run a loop from 1 to max(A, B) and can easily find X
6 min read
What is Bit Manipulation
Bit manipulation is the process of manipulating individual bits or groups of bits in a binary representation of data. It involves performing logical and arithmetic operations on binary digits or bits to achieve a desired result. How to Perform Bit Manipulation?Bit manipulation is performed using bit-wise operators, which operate on individual bits
4 min read
Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Space complexity is the most underestimated asset by programmers. One can barely see a Memory Limit Exceed (MLE) while submitting a solution. But, saving memory is the most important thing a programmer should take care about. If one needs to create an Application for a user, it should be made as memory efficient as one can. Boolean arrays have been
10 min read
Bit Manipulation for Competitive Programming
Bit manipulation is a technique in competitive programming that involves the manipulation of individual bits in binary representations of numbers. It is a valuable technique in competitive programming because it allows you to solve problems efficiently, often reducing time complexity and memory usage. Table of Content Bitwise OperatorsUseful Bitwis
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
Minimum Count of Bit flips required to make a Binary String Palindromic
Given an integer N, the task is to find the minimum number of bits required to be flipped to convert the binary representation of N into a palindrome. Examples: Input: N = 12 Output: 2 Explanation: Binary String representing 12 = "1100". To make "1100" a palindrome, convert the string to "0110". Therefore, minimum bits required to be flipped is 2.I
7 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
Count of 1-bit and 2-bit characters in the given binary string
Given two special characters, the first character can be represented by one bit which is 0 and the second character can be represented by two bits either 10 or 11. Now given a string represented by several bits. The task is to return the number of characters it represents. Note that the given string is always valid.Examples: Input: str = "11100" Ou
4 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
Mutation Algorithms for String Manipulation (GA)
Genetic Algorithms(GAs) are adaptive heuristic search algorithms that belong to the larger part of evolutionary algorithms. In each generation chromosomes(our solution candidates) undergo mutation and crossover and then selection to produce a better population whose candidates are nearer to our desired solution. Mutation Operator is a unary operato
2 min read
String Comparison and Manipulation Queries with Blocking and Swapping
Given Two strings S1 and S2 of equal length N, consisting of lowercase letters. There are also given integer T and Q queries. Each query can be one of three types, for queries of the first and second types, the specified positions and characters are not blocked. The task for this problem is to print the answer for query type 3. Type 1: {1, pos} Blo
15+ min read