Open In App

Minimum equal palindromic cuts with rearrangements allowed

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string of length n. Find the minimum number of possible cuts after rearranging the string (if required), such that each cut is a palindrome and length of every cut is equal. That is, find the minimum number of palindromes of equal lengths that can be obtained by partitioning the given string if rearrangement of string is allowed before partitioning.

Examples: 

Input : string = "aabaac"
Output : 2
Explanation : Rearrange the string as "abaaca"
              and cut into "aba" and "aca"

Input : string = "aabbccdd"
Output : 1
Explanation : Rearrange the string as "abcddcba"
              This is a palindrome and cannot be 
              cut further.

If we observe carefully, our problem reduces to calculating characters with odds and even counts. Below are the possible cases, 

  1. If the characters present in the string have only even counts then the answer will be 1 as we can rearrange the entire string to form a palindrome. 
  2. If there is only one character with odd count, then also the answer will be 1 as we can 
    rearrange the entire string to form a palindrome. 
  3. If there is more than one character with odd count, then we will create two separate list of characters – one for odd characters and one for even characters. Now, if we notice that if a character has odd count then if we subtract 1 from it, the count will become even. So we will insert the element with odd counts only once in the odd list. We will insert the elements with even counts (evenCount/2) times, i.e. half of their count in the even list. Now our problem is to uniformly distribute the even count elements among odd count elements to form palindromes of equal length. Suppose the list of even count characters is even and odd count characters is odd. If even.size() is divisible by odd.size() our answer will be odd.size() otherwise we will transfer elements from even list to odd list until even.size() is divisible by odd.size(). 

Below is the implementation of above idea: 

CPP




// CPP program to find minimum number of palindromic
// cuts of equal length
#include<bits/stdc++.h>
using namespace std;
 
// function to find minimum number of
// palindromic cuts of equal length
int minPalindromeCuts(string str)
{  
    // map to store count of characters
    unordered_map<char,int> m;
     
    // store count of characters in a map
    for (int i=0;i<str.length();i++)
    {
       if (m.find(str[i])==m.end())
            m.insert(make_pair(str[i],1));
       else
            m[str[i]]++;
    }
     
    // list to store even count characters
    vector<char> even;
     
    // list to store odd count characters
    vector<char> odd;
     
    for (auto itr = m.begin(); itr!=m.end(); itr++)
    
        // add odd count characters only once and
        // decrement count by 1
        if (itr->second%2!=0)
        {
            odd.push_back(itr->first);
            itr->second--;
        }
    }
     
    for (auto itr = m.begin(); itr!=m.end(); itr++)
    {
        if (itr->second%2==0)
        {  
            // add even count characters half of their
            // count to the even list so that we can
            // simply repeat the even list on both
            // sides of an odd char to generate a
            // palindrome
            for (int i=0;i<(itr->second)/2;i++)           
                even.push_back(itr->first);
        }
    }
     
    // if there is no odd count characters or
    // only 1 odd count character, return 1
    if (odd.size() <= 1)   
        return 1;
     
    else
    {
        // Move some characters from even list over
        // to odd list to make palindrome work
        while (odd.size() > 0 && even.size() > 0 &&
               even.size() % odd.size() != 0)
        {
            odd.push_back(even.back());
            odd.push_back(even.back());
            even.pop_back();
        }
         
        return odd.size();
    }
}
 
// driver code
int main()
{
    string str = "aabaac";   
    cout << minPalindromeCuts(str);
    return 0;
}


Java




// Java Program for the above approach
 
import java.util.*;
 
public class Main {
    // function to find minimum number of palindromic cuts of equal length
    public static int minPalindromeCuts(String str) {
        // map to store count of characters
        Map<Character, Integer> m = new HashMap<>();
 
        // store count of characters in a map
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (!m.containsKey(ch))
                m.put(ch, 1);
            else
                m.put(ch, m.get(ch) + 1);
        }
 
        // list to store even count characters
        List<Character> even = new ArrayList<>();
 
        // list to store odd count characters
        List<Character> odd = new ArrayList<>();
 
        for (Map.Entry<Character, Integer> entry : m.entrySet()) {
            char ch = entry.getKey();
            int count = entry.getValue();
 
            // add odd count characters only once and
            // decrement count by 1
            if (count % 2 != 0) {
                odd.add(ch);
                entry.setValue(count - 1);
            }
        }
 
        for (Map.Entry<Character, Integer> entry : m.entrySet()) {
            char ch = entry.getKey();
            int count = entry.getValue();
 
            if (count % 2 == 0) {
                // add even count characters half of their
                // count to the even list so that we can
                // simply repeat the even list on both
                // sides of an odd char to generate a
                // palindrome
                for (int i = 0; i < count / 2; i++)
                    even.add(ch);
            }
        }
 
        // if there is no odd count characters or
        // only 1 odd count character, return 1
        if (odd.size() <= 1)
            return 1;
 
        else {
            // Move some characters from even list over
            // to odd list to make palindrome work
            while (odd.size() > 0 && even.size() > 0 && even.size() % odd.size() != 0) {
                odd.add(even.get(even.size() - 1));
                odd.add(even.get(even.size() - 1));
                even.remove(even.size() - 1);
            }
 
            return odd.size();
        }
    }
 
    // driver code
    public static void main(String[] args) {
        String str = "aabaac";
        System.out.println(minPalindromeCuts(str));
    }
}
 
// This code is contributed by Prince


Python3




# Python program to find minimum number of palindromic
# cuts of equal length
 
# function to find minimum number of
# palindromic cuts of equal length
def minPalindromeCuts(Str):
 
    # map to store count of characters
    m = {}
     
    # store count of characters in a map
    for i in range(len(Str)):
        if (Str[i] not in m):
            m[Str[i]] = 1
        else:
            m[Str[i]] += 1
     
    # list to store even count characters
    even = []
     
    # list to store odd count characters
    odd = []
     
    for itr1,itr2 in m.items():
 
        # add odd count characters only once and
        # decrement count by 1
        if (itr2 % 2 != 0):
            odd.append(itr1)
            itr2 -= 1
     
    for itr1,itr2 in m.items():
 
        if (itr2%2==0):
            # add even count characters half of their
            # count to the even list so that we can
            # simply repeat the even list on both
            # sides of an odd char to generate a
            # palindrome
            for i in range(itr2//2):       
                even.append(itr1)
     
    # if there is no odd count characters or
    # only 1 odd count character, return 1
    if (len(odd)<= 1):
        return 1
     
    else:
 
        # Move some characters from even list over
        # to odd list to make palindrome work
        while (len(odd)> 0 and len(even) > 0 and len(even) % len(odd)!= 0):
 
            odd.append(even[-1])
            odd.append(even[-1])
            even.pop()
         
        return len(odd)
 
# driver code
 
Str = "aabaac"
print(minPalindromeCuts(Str))
 
# This code is contributed by Shinjanpatra


C#




// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
public class MainClass {
    public static int MinPalindromeCuts(string str) {
        // map to store count of characters
        Dictionary<char, int> m = new Dictionary<char, int>();
 
        // store count of characters in a map
        for (int i = 0; i < str.Length; i++) {
            char ch = str[i];
            if (!m.ContainsKey(ch))
                m[ch] = 1;
            else
                m[ch]++;
        }
 
        // list to store even count characters
        List<char> even = new List<char>();
 
        // list to store odd count characters
        List<char> odd = new List<char>();
 
        foreach (KeyValuePair<char,
                 int> entry in new Dictionary<char, int>(m)) {
            char ch = entry.Key;
            int count = entry.Value;
 
            // add odd count characters only once and
            // decrement count by 1
            if (count % 2 != 0) {
                odd.Add(ch);
                m[ch] = count - 1;
            }
        }
 
        foreach (KeyValuePair<char, int> entry in new Dictionary<char, int>(m)) {
            char ch = entry.Key;
            int count = entry.Value;
 
            if (count % 2 == 0) {
                // add even count characters half of their
                // count to the even list so that we can
                // simply repeat the even list on both
                // sides of an odd char to generate a
                // palindrome
                for (int i = 0; i < count / 2; i++)
                    even.Add(ch);
            }
        }
 
        // if there is no odd count characters or
        // only 1 odd count character, return 1
        if (odd.Count <= 1)
            return 1;
 
        else {
            // Move some characters from even list over
            // to odd list to make palindrome work
            while (odd.Count > 0 && even.Count > 0 &&
                   even.Count % odd.Count != 0) {
                odd.Add(even[even.Count - 1]);
                odd.Add(even[even.Count - 1]);
                even.RemoveAt(even.Count - 1);
            }
 
            return odd.Count;
        }
    }
 
    public static void Main(string[] args) {
        string str = "aabaac";
        Console.WriteLine(MinPalindromeCuts(str));
    }
}
 
// This codeis contributed by adityashatmfh


Javascript




<script>
 
// JavaScript program to find minimum number of palindromic
// cuts of equal length
 
// function to find minimum number of
// palindromic cuts of equal length
function minPalindromeCuts(str){
 
    // map to store count of characters
    let m = new Map();
     
    // store count of characters in a map
    for (let i = 0; i < str.length; i++)
    {
        if (m.has(str[i]) == false)
            m.set(str[i], 1);
        else
            m.set(str[i], m.get(str[i]) + 1);
    }
     
    // list to store even count characters
    let even = [];
     
    // list to store odd count characters
    let odd = [];
     
    for (let [itr1,itr2] of m)
    {
        // add odd count characters only once and
        // decrement count by 1
        if (itr2%2!=0)
        {
            odd.push(itr1);
            itr2--;
        }
    }
     
    for (let [itr1,itr2] of m)
    {
        if (itr2%2==0)
        {
            // add even count characters half of their
            // count to the even list so that we can
            // simply repeat the even list on both
            // sides of an odd char to generate a
            // palindrome
            for (let i=0;i<Math.floor((itr2)/2);i++)       
                even.push(itr1);
        }
    }
     
    // if there is no odd count characters or
    // only 1 odd count character, return 1
    if (odd.length <= 1)
        return 1;
     
    else
    {
        // Move some characters from even list over
        // to odd list to make palindrome work
        while (odd.length > 0 && even.length > 0 &&
            even.length % odd.length != 0)
        {
            odd.push(even[even.length - 1]);
            odd.push(even[even.length - 1]);
            even.pop();
        }
         
        return odd.length;
    }
}
 
// driver code
 
let str = "aabaac";
document.write(minPalindromeCuts(str));
 
// This code is contributed by Shinjanpatra
 
</script>


Output

2

Time Complexity:  O(N2)
Auxiliary Space: O(N)



Last Updated : 06 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads