Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Maximum length palindromic substring such that it starts and ends with given char
Next article icon

Maximum even length sub-string that is permutation of a palindrome

Last Updated : 08 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given string [Tex]str        [/Tex], the task is to find the maximum length of the sub-string of [Tex]str        [/Tex]that can be arranged into a Palindrome (i.e at least one of its permutation is a Palindrome). 

Note that the sub-string must be of even length. 

Examples:

Input: str = “124565463” 
Output: 6 “456546” is the valid sub-string 

Input: str = “122313” 
Output: 6

Approach: 

Use two variables: start (inclusive) and end (exclusive) to keep track of the starting and ending index of the current sub-string that is being considered in the given string. Also use a dictionary named count which keeps the record of how many times, a character occurs in the current sub-string. 

Now, there are two possible cases for a sub-string:

  1. If the length of the sub-string is odd, then it cannot be considered in the final solution.
  2. If the length of the sub-string is even, then it can be a possible solution only if each character in that sub-string occurs even number of times which can be done using the dictionary count. We check if each character occurs an even number of times or not. If yes, then we include it as one of the possible solutions. Then we form the next sub-string by including the next character in the string which can be done by simply incrementing the end and check recursively if a sub-string with greater length can be formed which satisfies the given conditions and return the maximum of all possible solutions.

Below is the implementation of the above approach: 

C++

// C++ code to find the maximum length of
// sub-string (of even length) which can be
// arranged into a Palindrome
#include <bits/stdc++.h>
using namespace std;
 
unordered_map<int, int> countt;
 
// function that returns true if the given
// sub-string can be arranged into a Palindrome
bool canBePalindrome(unordered_map<int, int> &countt)
{
    for (auto key : countt)
    {
        if (key.second & 1) return false;
    }
    return true;
}
 
// This function returns the maximum length of
// the sub-string (of even length) which can be
// arranged into a Palindrome
int maxPal(string str,
           unordered_map<int, int> &countt,
           int start, int end)
{
     
    // If we reach end of the string
    if (end == str.length())
    {
 
        // if string is of even length
        if ((end - start) % 2 == 0)
 
            // if string can be arranged into a
            // palindrome
            if (canBePalindrome(countt)) return end - start;
 
        return 0;
    }
    else
    {
 
        // Even length sub-string
        if ((end - start) % 2 == 0)
        {
 
            // Check if current sub-string can be
            // arranged into a palindrome
            if (canBePalindrome(countt))
            {
                countt[str[end]]++;
                return max(end - start, maxPal(str, countt,
                                               start, end + 1));
            }
            else
            {
                countt[str[end]]++;
                return maxPal(str, countt, start, end + 1);
            }
        }
 
        // Odd length sub-string
        else
        {
            countt[str[end]]++;
            unordered_map<int, int> c(countt.begin(),
                                      countt.end());
            int length = maxPal(str, c, start, end + 1);
 
            countt[str[end]]--;
            countt[str[start]]--;
            return max(length, maxPal(str, countt,
                                      start + 1, end));
        }
    }
}
 
// Driver code
int main(int argc, char const *argv[])
{
    string str = "124565463";
    int start = 0, end = 0;
 
    cout << maxPal(str, countt, start, end) << endl;
    return 0;
}
 
// This code is contributed by
// sanjeev2552
                      
                       

Java

// Java code to find the maximum length of
// sub-string (of even length) which can be
// arranged into a Palindrome
import java.io.*;
import java.util.*;
 
class GFG
{
 
    static HashMap<Integer, Integer> count = new HashMap<>();
 
    // function that returns true if the given
    // sub-string can be arranged into a Palindrome
    static boolean canBePalindrome(HashMap<Integer, Integer> count)
    {
        for (HashMap.Entry<Integer, Integer> entry : count.entrySet())
            if ((entry.getValue() & 1) == 1)
                return false;
        return true;
    }
 
    // This function returns the maximum length of
    // the sub-string (of even length) which can be
    // arranged into a Palindrome
    static int maxPal(String str, int start, int end,
                       HashMap<Integer, Integer> count)
    {
 
        // If we reach end of the string
        if (end == str.length())
        {
 
            // if string is of even length
            if ((end - start) % 2 == 0)
 
                // if string can be arranged into a
                // palindrome
                if (canBePalindrome(count))
                    return end - start;
 
            return 0;
        }
        else
        {
 
            // Even length sub-string
            if ((end - start) % 2 == 0)
            {
 
                // Check if current sub-string can be
                // arranged into a palindrome
                if (canBePalindrome(count))
                {
                    count.put((int) str.charAt(end),
                    count.get((int) str.charAt(end)) ==
                    null ? 1 : count.get((int) str.charAt(end)) + 1);
                    return Math.max(end - start,
                            maxPal(str, start, end + 1, count));
                }
                else
                {
                    count.put((int) str.charAt(end),
                    count.get((int) str.charAt(end)) ==
                    null ? 1 : count.get((int) str.charAt(end)) + 1);
                    return maxPal(str, start, end + 1, count);
                }
            }
 
            // Odd length sub-string
            else
            {
                count.put((int) str.charAt(end),
                count.get((int) str.charAt(end)) ==
                null ? 1 : count.get((int) str.charAt(end)) + 1);
                HashMap<Integer, Integer> c = new HashMap<>(count);
 
                int length = maxPal(str, start, end + 1, c);
 
                count.put((int) str.charAt(end),
                count.get((int) str.charAt(end)) ==
                null ? -1 : count.get((int) str.charAt(end)) - 1);
                 
                count.put((int) str.charAt(start),
                count.get((int) str.charAt(start)) ==
                null ? -1 : count.get((int) str.charAt(start)) - 1);
 
                return Math.max(length, maxPal(str,
                            start + 1, end, count));
            }
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String str = "124565463";
        int start = 0, end = 0;
        System.out.println(maxPal(str, start, end, count));
    }
}
 
// This code is contributed by
// sanjeev2552
                      
                       

Python3

# Python3 code to find the maximum length of sub-string
# (of even length) which can be arranged into a Palindrome
 
from collections import defaultdict
 
# function that returns true if the given
# sub-string can be arranged into a Palindrome
def canBePalindrome(count):   
    for key in count:
        if count[key] % 2 != 0:
            return False           
    return True
     
# This function returns the maximum length of
# the sub-string (of even length) which can be
# arranged into a Palindrome
def maxPal(string, count, start, end):
     
    # If we reach end of the string
    if end == len(string):
 
        # if string is of even length
        if (end-start) % 2 == 0:
 
            # if string can be arranged into a
            # palindrome
            if canBePalindrome(count) == True:
                return end-start
                 
        return 0
         
    else:
         
        # Even length sub-string
        if (end-start) % 2 == 0:
             
            # Check if current sub-string can be
            # arranged into a palindrome
            if canBePalindrome(count) == True:
                count[string[end]] += 1
                return max(end-start, maxPal(string, count, start, end + 1))
                 
            else:
                count[string[end]] += 1
                return maxPal(string, count, start, end + 1)
         
        # Odd length sub-string 
        else:
             
            count[string[end]] += 1
            length = maxPal(string, count.copy(), start, end + 1)
             
            count[string[end]] -= 1
            count[string[start]] -= 1
            return max(length, maxPal(string, count, start + 1, end))
             
# Driver code
string = '124565463'
start, end = 0, 0
count = defaultdict(lambda : 0)
 
print(maxPal(string, count, start, end))
                      
                       

C#

using System;
using System.Collections.Generic;
 
public class GFG
{
  static Dictionary<int, int> count = new Dictionary<int, int>();
 
  // function that returns true if the given
  // sub-string can be arranged into a Palindrome
  static bool CanBePalindrome(Dictionary<int, int> count)
  {
    foreach (KeyValuePair<int, int> entry in count)
      if ((entry.Value & 1) == 1)
        return false;
    return true;
  }
 
  // This function returns the maximum length of
  // the sub-string (of even length) which can be
  // arranged into a Palindrome
  static int MaxPal(string str, int start, int end,
                    Dictionary<int, int> count)
  {
    // If we reach end of the string
    if (end == str.Length)
    {
      // if string is of even length
      if ((end - start) % 2 == 0)
      {
        // if string can be arranged into a
        // palindrome
        if (CanBePalindrome(count))
          return end - start;
 
        return 0;
      }
      else
      {
        return 0;
      }
    }
    else
    {
      // Even length sub-string
      if ((end - start) % 2 == 0)
      {
        // Check if current sub-string can be
        // arranged into a palindrome
        if (CanBePalindrome(count))
        {
          count[str[end]] = count.ContainsKey(str[end]) ?
            count[str[end]] + 1 : 1;
          return Math.Max(end - start,
                          MaxPal(str, start, end + 1, count));
        }
        else
        {
          count[str[end]] = count.ContainsKey(str[end]) ?
            count[str[end]] + 1 : 1;
          return MaxPal(str, start, end + 1, count);
        }
      }
      // Odd length sub-string
      else
      {
        count[str[end]] = count.ContainsKey(str[end]) ?
          count[str[end]] + 1 : 1;
        Dictionary<int, int> c = new Dictionary<int, int>(count);
 
        int length = MaxPal(str, start, end + 1, c);
 
        count[str[end]] = count.ContainsKey(str[end]) ?
          count[str[end]] - 1 : -1;
 
        count[str[start]] = count.ContainsKey(str[start]) ?
          count[str[start]] - 1 : -1;
 
        return Math.Max(length, MaxPal(str,
                                       start + 1, end, count));
      }
    }
  }
 
  // Driver Code
  public static void Main()
  {
    string str = "124565463";
    int start = 0, end = 0;
    Console.WriteLine(MaxPal(str, start, end, count));
  }
}
                      
                       

Javascript

// Javacript program for the above approach
 
// function that returns true if the given
// sub-string can be arranged into a Palindrome
function canBePalindrome(count) {
  for (let key in count) {
    if (count[key] % 2 !== 0) {
      return false;
    }
  }
  return true;
}
 
// This function returns the maximum length of
// the sub-string (of even length) which can be
// arranged into a Palindrome
function maxPal(string, count, start, end)
{
 
  // If we reach end of the string
  if (end === string.length) {
   
    // if string is of even length
    if ((end - start) % 2 === 0) {
     
      // if string can be arranged into a palindrome
      if (canBePalindrome(count) === true) {
        return end - start;
      }
      return 0;
    } else {
      return 0;
    }
  } else {
    // Even length sub-string
    if ((end - start) % 2 === 0) {
     
      // Check if current sub-string can be
      // arranged into a palindrome
      if (canBePalindrome(count) === true) {
        count[string[end]] = (count[string[end]] || 0) + 1;
        return Math.max(end - start, maxPal(string, {...count}, start, end + 1));
      } else {
        count[string[end]] = (count[string[end]] || 0) + 1;
        return maxPal(string, {...count}, start, end + 1);
      }
    } else {
      count[string[end]] = (count[string[end]] || 0) + 1;
      let length = maxPal(string, {...count}, start, end + 1);
      count[string[end]] -= 1;
      count[string[start]] = (count[string[start]] || 0) - 1;
      return Math.max(length, maxPal(string, {...count}, start + 1, end));
    }
  }
}
 
// Driver code
let string = '124565463';
let start = 0;
let end = 0;
let count = {};
 
console.log(maxPal(string, count, start, end));
 
// This code is contributed by codebraxnzt
                      
                       

Output
6

Time Complexity: O(n * 2^n)

Auxiliary space: O(n)



Next Article
Maximum length palindromic substring such that it starts and ends with given char

R

rituraj_jain
Improve
Article Tags :
  • DSA
  • Strings
  • Technical Scripter
  • palindrome
  • Technical Scripter 2018
Practice Tags :
  • palindrome
  • Strings

Similar Reads

  • Permutation of given string that maximizes count of Palindromic substrings
    Given a string S, the task is to find the permutation of the string such that palindromic substrings in the string are maximum.Note: There can be multiple answers for each string. Examples: Input: S = "abcb" Output: "abbc" Explanation: "abbc" is the string with maximum number of palindromic substrin
    3 min read
  • Minimum length of substring whose rotation generates a palindromic substring
    Given a string str, the task is to find the minimum length of substring required to rotate that generates a palindromic substring from the given string. Examples: Input: str = "abcbd" Output: 0 Explanation: No palindromic substring can be generated. There is no repeated character in the string. Inpu
    7 min read
  • Minimum length of string having all permutation of given string.
    Given a string [Tex]S [/Tex]where [Tex]1\leq length\; of\; S\leq 26 [/Tex]. Assume that all the characters in [Tex]S [/Tex]are unique. The task is to compute the minimum length of a string which consists of all the permutations of the given string in any order. Note: All permutations must be present
    4 min read
  • Maximum length palindromic substring such that it starts and ends with given char
    Given a string str and a character ch, the task is to find the longest palindromic sub-string of str such that it starts and ends with the given character ch.Examples: Input: str = "lapqooqpqpl", ch = 'p' Output: 6 "pqooqp" is the maximum length palindromic sub-string that starts and ends with 'p'.I
    7 min read
  • Minimum removal of characters required such that permutation of given string is a palindrome
    Given string str consisting of lowercase letters, the task is to find the minimum number of characters to be deleted from the given string such that any permutation of the remaining string is a palindrome. Examples: Input: str="aba"Output: 1Explanation: Removing 'b' generates a palindromic string "a
    7 min read
  • Count maximum-length palindromes in a String
    Given a string, count how many maximum-length palindromes are present. (It need not be a substring) Examples: Input : str = "ababa" Output: 2 Explanation : palindromes of maximum of lengths are : "ababa", "baaab" Input : str = "ababab" Output: 4 Explanation : palindromes of maximum of lengths are :
    9 min read
  • Check if all the palindromic sub-strings are of odd length
    Given a string 's' check if all of its palindromic sub-strings are of odd length or not. If yes then print "YES" or "NO" otherwise. Examples: Input: str = "geeksforgeeks" Output: NO Since, "ee" is a palindromic sub-string of even length. Input: str = "madamimadam" Output: YES Brute Force Approach: S
    10 min read
  • Maximize the minimum length of K palindromic Strings formed from given String
    Given a string str of length N, and an integer K, the task is to form K different strings by choosing characters from the given string such that all the strings formed are palindrome and the length of the smallest string among the K strings is maximum possible. Examples: Input: str = "qrsprtps", K =
    10 min read
  • Minimum replacements such that no palindromic substring of length exceeding 1 is present in the given string
    Given a string str consisting of lowercase characters, the task is to modify the string such that it does not contain any palindromic substring of length exceeding 1 by minimum replacement of characters. Examples: Input: str = �"Output: 4String can be modified to "bacbacb" by replacing 4 characters.
    9 min read
  • Check if string can be rearranged so that every Odd length Substring is Palindrome
    Given a string S. The task is to check whether it is possible to rearrange the string such that every substring of odd length is a palindrome. Examples: Input: S = "oiooi" Output: YES The string can be rearranged as "oioio" Input: S = "yuyuo" Output: NO Approach: The very first observation is if all
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences