Minimum equal palindromic cuts with rearrangements allowed
Last Updated :
06 Mar, 2023
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,
- 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.
- 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. - 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>
Time Complexity: O(N2)
Auxiliary Space: O(N)
Similar Reads
Palindrome String Coding Problems A string is called a palindrome if the reverse of the string is the same as the original one.Example: âmadamâ, âracecarâ, â12321â.Palindrome StringProperties of a Palindrome String:A palindrome string has some properties which are mentioned below:A palindrome string has a symmetric structure which m
2 min read
Palindrome String Given a string s, the task is to check if it is palindrome or not.Example:Input: s = "abba"Output: 1Explanation: s is a palindromeInput: s = "abc" Output: 0Explanation: s is not a palindromeUsing Two-Pointers - O(n) time and O(1) spaceThe idea is to keep two pointers, one at the beginning (left) and
13 min read
Check Palindrome by Different Language
Easy Problems on Palindrome
Sentence Palindrome Given a sentence s, the task is to check if it is a palindrome sentence or not. A palindrome sentence is a sequence of characters, such as a word, phrase, or series of symbols, that reads the same backward as forward after converting all uppercase letters to lowercase and removing all non-alphanumer
9 min read
Check if actual binary representation of a number is palindrome Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0âs are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Inp
6 min read
Print longest palindrome word in a sentence Given a string str, the task is to print longest palindrome word present in the string str.Examples: Input : Madam Arora teaches Malayalam Output: Malayalam Explanation: The string contains three palindrome words (i.e., Madam, Arora, Malayalam) but the length of Malayalam is greater than the other t
14 min read
Count palindrome words in a sentence Given a string str and the task is to count palindrome words present in the string str. Examples: Input : Madam Arora teaches malayalam Output : 3 The string contains three palindrome words (i.e., Madam, Arora, malayalam) so the count is three. Input : Nitin speaks malayalam Output : 2 The string co
5 min read
Check if characters of a given string can be rearranged to form a palindrome Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
14 min read
Lexicographically first palindromic string Rearrange the characters of the given string to form a lexicographically first palindromic string. If no such string exists display message "no palindromic string". Examples: Input : malayalam Output : aalmymlaa Input : apple Output : no palindromic string Simple Approach: 1. Sort the string charact
13 min read