Longest substring whose characters can be rearranged to form a Palindrome
Last Updated :
15 Jul, 2025
Given a string S of length N which only contains lowercase alphabets. Find the length of the longest substring of S such that the characters in it can be rearranged to form a palindrome.
Examples:
Input: S = “aabe”
Output: 3
Explanation:
The substring “aab” can be rearranged to form "aba", which is a palindromic substring.
Since the length of “aab” is 3 so output is 3.
Notice that "a", "aa", "b" and "e" can be arranged to form palindromic strings, but they are not longer than “aab”.
Input: S = "adbabd"
Output: 6
Explanation:
The whole string "adbabd" can be rearranged to form a palindromic substring. One possible arrangement is "abddba".
Therefore, output length of the string i.e., 6.
Naive Approach: The idea is to generate all possible substring and keep count of each character in it. Initialize answer with the value 0. If the count of each character is even with at most one character with the odd occurrence, the substring can be re-arranged to form a palindromic string. If a substring satisfies this property then update the answer. Print the maximum length after the above steps.
Below is the implementation of the above approach:
C++
// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
// function to check if the string can be
// rearranged to a palindromic string or not
bool ispalindromic(string s)
{
int n = s.size();
// hashmap to count the frequency of
// every character in given substring
unordered_map<char, int> hashmap;
for (auto ch : s) {
hashmap[ch]++;
}
int count = 0;
// Count of characters having odd frequency
for (auto i : hashmap) {
if (i.second % 2 == 1)
count++;
}
// if count is greater than 1
if (count > 1) {
return false;
}
return true;
}
// Function to get the length of longest
// substring whose characters can be
// arranged to form a palindromic string
int longestSubstring(string S, int n)
{
int ans = 0;
for (int i = 0; i < S.size(); i++) {
string curstr = "";
for (int j = i; j < S.size(); j++) {
// Storing the substring
curstr += S[j];
// Checking if it is possible to
// make it a palindrome
if (ispalindromic(curstr)
== true)
{
// Storing the maximum answer
ans = max(ans, j - i + 1);
}
}
}
return ans;
}
// Driver code
int main()
{
// Given String
string s = "adbabd";
// Length of given string
int n = s.size();
// Function call
cout << (longestSubstring(s, n));
}
// This code is contributed by Arpit Jain
Java
// Java code for the above approach
import java.io.*;
import java.util.*;
class GFG {
// function to check if the string can be
// rearranged to a palindromic string or not
static boolean ispalindromic(String s)
{
int n = s.length();
// hashmap to count the frequency of
// every character in given substring
HashMap<Character,Integer>hashmap = new HashMap<Character,Integer>();
for (int ch = 0; ch < n; ch++) {
if(hashmap.containsKey(s.charAt(ch))){
hashmap.put(s.charAt(ch), hashmap.get(s.charAt(ch))+1);
}
else hashmap.put(s.charAt(ch),1);
}
int count = 0;
// Count of characters having odd frequency
for(Character i : hashmap.keySet()){
if (hashmap.get(i) % 2 == 1)
count++;
}
// if count is greater than 1
if (count > 1) {
return false;
}
return true;
}
// Function to get the length of longest
// substring whose characters can be
// arranged to form a palindromic string
static int longestSubstring(String S, int n)
{
int ans = 0;
for (int i = 0; i < S.length(); i++) {
String curstr = "";
for (int j = i; j < S.length(); j++) {
// Storing the substring
curstr += S.charAt(j);
// Checking if it is possible to
// make it a palindrome
if (ispalindromic(curstr)
== true)
{
// Storing the maximum answer
ans = Math.max(ans, j - i + 1);
}
}
}
return ans;
}
// Driver code
public static void main (String[] args)
{
// Given String
String s = "adbabd";
// Length of given string
int n = s.length();
// Function call
System.out.println(longestSubstring(s, n));
}
}
// This code is contributed by Aman Kumar.
Python
# Python code for the above approach
# function to check if the string can be
# rearranged to a palindromic string or not
def ispalindromic(s):
n = len(s)
# hashmap to count the frequency of
# every character in given substring
hashmap={}
for ch in s:
if(ch in hashmap):
hashmap[ch] = hashmap[ch] + 1
else:
hashmap[ch] = 1
count = 0
# Count of characters having odd frequency
for key in hashmap:
if(hashmap[key]%2 == 1):
count += 1
# if count is greater than 1
if(count > 1):
return False
return True
# Function to get the length of longest
# substring whose characters can be
# arranged to form a palindromic string
def longestSubstring(S, n):
ans = 0
for i in range(len(S)):
curstr = ""
for j in range(i,len(S)):
# Storing the substring
curstr += S[j]
# Checking if it is possible to
# make it a palindrome
if(ispalindromic(curstr) == True):
# Storing the maximum answer
ans = max(ans, j - i + 1)
return ans
# Driver code
# Given String
s = "adbabd"
# Length of given string
n = len(s)
# Function call
print(longestSubstring(s,n))
# This code is contributed by Pushpesh Raj.
C#
// C# code for the above approach
using System;
using System.Collections.Generic;
class GFG {
// function to check if the string can be
// rearranged to a palindromic string or not
static bool ispalindromic(string s)
{
int n = s.Length;
// hashmap to count the frequency of
// every character in given substring
Dictionary<char,int> hashmap = new Dictionary<char,int>();
for (int ch = 0; ch < n; ch++) {
if(hashmap.ContainsKey(s[ch])){
hashmap[s[ch]] = hashmap[s[ch]]+1;
}
else hashmap.Add(s[ch],1);
}
int count = 0;
// Count of characters having odd frequency
foreach(KeyValuePair<char,int> i in hashmap){
if (i.Value % 2 == 1)
count++;
}
// if count is greater than 1
if (count > 1) {
return false;
}
return true;
}
// Function to get the length of longest
// substring whose characters can be
// arranged to form a palindromic string
static int longestSubstring(string S, int n)
{
int ans = 0;
for (int i = 0; i < S.Length; i++) {
string curstr = "";
for (int j = i; j < S.Length; j++) {
// Storing the substring
curstr += S[j];
// Checking if it is possible to
// make it a palindrome
if (ispalindromic(curstr)
== true)
{
// Storing the maximum answer
ans = Math.Max(ans, j - i + 1);
}
}
}
return ans;
}
// Driver code
public static void Main()
{
// Given String
string s = "adbabd";
// Length of given string
int n = s.Length;
// Function call
Console.WriteLine(longestSubstring(s, n));
}
}
// This code is contributed by Utkarsh
JavaScript
// Javascript code for the above approach
// function to check if the string can be
// rearranged to a palindromic string or not
function ispalindromic(s) {
let n = s.length;
// hashmap to count the frequency of
// every character in given substring
let hashmap = {};
for (let i = 0; i < n; i++) {
if (!hashmap[s[i]]) {
hashmap[s[i]] = 1;
} else {
hashmap[s[i]]++;
}
}
let count = 0;
// Count of characters having odd frequency
for (let key in hashmap) {
if (hashmap[key] % 2 === 1) count++;
}
// if count is greater than 1
if (count > 1) {
return false;
}
return true;
}
// Function to get the length of longest
// substring whose characters can be
// arranged to form a palindromic string
function longestSubstring(S) {
let ans = 0;
for (let i = 0; i < S.length; i++) {
let curstr = "";
for (let j = i; j < S.length; j++) {
// Storing the substring
curstr += S[j];
// Checking if it is possible to
// make it a palindrome
if (ispalindromic(curstr) === true) {
// Storing the maximum answer
ans = Math.max(ans, j - i + 1);
}
}
}
return ans;
}
// Given String
let s = "adbabd";
// Length of given string
let n = s.length;
// Function call
console.log(longestSubstring(s));
// This code is contributed by lokeshpotta20.
Time Complexity: O(N3 * 26)
Auxiliary Space: O(N2 * 26)
Efficient Approach: The idea is to observe that the string is a palindrome if at most one character occurs an odd number of times. So there is no need to keep the total count of each character. Just knowing that it is occurring even or an odd number of times is enough. To do this, use bit masking since the count of lowercase alphabets is only 26.
- Define a bitmask variable mask which tracks if the occurrence of each character is even or odd.
- Create a dictionary index that keeps track of the index of each bitmask.
- Traverse the given string S. First, convert the characters from 'a' - 'z' to 0 - 25 and store this value in a variable temp. For each occurrence of the character, take Bitwise XOR of 2temp with the mask.
- If the character occurs even number of times, its bit in the mask will be off else it will be on. If the mask is currently not in the index, simply assign present index i to bitmask mask in the index.
- If the mask is present in the index it means that from the index[mask] to i, the occurrence of all characters is even which is suitable for a palindromic substring. Therefore, update the answer if the length of this segment from the index[mask] to i is greater than the answer.
- To check for the substring with one character occurring an odd number of times, iterate a variable j over [0, 25]. Store Bitwise XOR of x with 2j in mask2.
- If mask2 is present in the index, this means that this character is occurring an odd number of times and all characters occur even a number of times in the segment index[mask2] to i, which is also a suitable condition for a palindromic string. Therefore, update our answer with the length of this substring if it is greater than the answer.
- Print the maximum length of substring after the above steps.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include<bits/stdc++.h>
using namespace std;
// Function to get the length of longest
// substring whose characters can be
// arranged to form a palindromic string
int longestSubstring(string s, int n)
{
// To keep track of the last
// index of each xor
map<int, int> index;
// Initialize answer with 0
int answer = 0;
int mask = 0;
index[mask] = -1;
// Now iterate through each character
// of the string
for(int i = 0; i < n; i++)
{
// Convert the character from
// [a, z] to [0, 25]
int temp = (int)s[i] - 97;
// Turn the temp-th bit on if
// character occurs odd number
// of times and turn off the temp-th
// bit off if the character occurs
// ever number of times
mask ^= (1 << temp);
// If a mask is present in the index
// Therefore a palindrome is
// found from index[mask] to i
if (index[mask])
{
answer = max(answer,
i - index[mask]);
}
// If x is not found then add its
// position in the index dict.
else
index[mask] = i;
// Check for the palindrome of
// odd length
for(int j = 0; j < 26; j++)
{
// We cancel the occurrence
// of a character if it occurs
// odd number times
int mask2 = mask ^ (1 << j);
if (index[mask2])
{
answer =max(answer,
i - index[mask2]);
}
}
}
return answer;
}
// Driver code
int main ()
{
// Given String
string s = "adbabd";
// Length of given string
int n = s.size();
// Function call
cout << (longestSubstring(s, n));
}
// This code is contributed by Stream_Cipher
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to get the length of longest
// substring whose characters can be
// arranged to form a palindromic string
static int longestSubstring(String s, int n)
{
// To keep track of the last
// index of each xor
Map<Integer, Integer> index = new HashMap<>();
// Initialize answer with 0
int answer = 0;
int mask = 0;
index.put(mask, -1);
// Now iterate through each character
// of the string
for(int i = 0; i < n; i++)
{
// Convert the character from
// [a, z] to [0, 25]
int temp = (int)s.charAt(i) - 97;
// Turn the temp-th bit on if
// character occurs odd number
// of times and turn off the temp-th
// bit off if the character occurs
// ever number of times
mask ^= (1 << temp);
// If a mask is present in the index
// Therefore a palindrome is
// found from index[mask] to i
if (index.containsKey(mask))
{
answer = Math.max(answer,
i - index.get(mask));
}
// If x is not found then add its
// position in the index dict.
else
index.put(mask,i);
// Check for the palindrome of
// odd length
for (int j = 0;j < 26; j++)
{
// We cancel the occurrence
// of a character if it occurs
// odd number times
int mask2 = mask ^ (1 << j);
if (index.containsKey(mask2))
{
answer = Math.max(answer,
i - index.get(mask2));
}
}
}
return answer;
}
// Driver code
public static void main (String[] args)
{
// Given String
String s = "adbabd";
// Length of given string
int n = s.length();
// Function call
System.out.print(longestSubstring(s, n));
}
}
// This code is contributed by offbeat
Python
# Python3 program for the above approach
# Function to get the length of longest
# substring whose characters can be
# arranged to form a palindromic string
def longestSubstring(s: str, n: int):
# To keep track of the last
# index of each xor
index = dict()
# Initialize answer with 0
answer = 0
mask = 0
index[mask] = -1
# Now iterate through each character
# of the string
for i in range(n):
# Convert the character from
# [a, z] to [0, 25]
temp = ord(s[i]) - 97
# Turn the temp-th bit on if
# character occurs odd number
# of times and turn off the temp-th
# bit off if the character occurs
# ever number of times
mask ^= (1 << temp)
# If a mask is present in the index
# Therefore a palindrome is
# found from index[mask] to i
if mask in index.keys():
answer = max(answer,
i - index[mask])
# If x is not found then add its
# position in the index dict.
else:
index[mask] = i
# Check for the palindrome of
# odd length
for j in range(26):
# We cancel the occurrence
# of a character if it occurs
# odd number times
mask2 = mask ^ (1 << j)
if mask2 in index.keys():
answer = max(answer,
i - index[mask2])
return answer
# Driver Code
# Given String
s = "adbabd"
# Length of given string
n = len(s)
# Function call
print(longestSubstring(s, n))
C#
// C# program for the above approach
using System.Collections.Generic;
using System;
class GFG{
// Function to get the length of longest
// substring whose characters can be
// arranged to form a palindromic string
static int longestSubstring(string s, int n)
{
// To keep track of the last
// index of each xor
Dictionary<int,
int> index = new Dictionary<int,
int>();
// Initialize answer with 0
int answer = 0;
int mask = 0;
index[mask] = -1;
// Now iterate through each character
// of the string
for(int i = 0; i < n; i++)
{
// Convert the character from
// [a, z] to [0, 25]
int temp = (int)s[i] - 97;
// Turn the temp-th bit on if
// character occurs odd number
// of times and turn off the temp-th
// bit off if the character occurs
// ever number of times
mask ^= (1 << temp);
// If a mask is present in the index
// Therefore a palindrome is
// found from index[mask] to i
if (index.ContainsKey(mask) == true)
{
answer = Math.Max(answer,
i - index[mask]);
}
// If x is not found then add its
// position in the index dict.
else
index[mask] = i;
// Check for the palindrome of
// odd length
for(int j = 0; j < 26; j++)
{
// We cancel the occurrence
// of a character if it occurs
// odd number times
int mask2 = mask ^ (1 << j);
if (index.ContainsKey(mask2) == true)
{
answer = Math.Max(answer,
i - index[mask2]);
}
}
}
return answer;
}
// Driver code
public static void Main ()
{
// Given String
string s = "adbabd";
// Length of given string
int n = s.Length;
// Function call
Console.WriteLine(longestSubstring(s, n));
}
}
// This code is contributed by Stream_Cipher
JavaScript
// JavaScript program for the above approach
// Function to get the length of longest
// substring whose characters can be
// arranged to form a palindromic string
function longestSubstring(s, n) {
// To keep track of the last
// index of each xor
var index = new Map();
// Initialize answer with 0
var answer = 0;
var mask = 0;
index.set(mask, -1);
// Now iterate through each character
// of the string
for (var i = 0; i < n; i++) {
// Convert the character from
// [a, z] to [0, 25]
var temp = s[i].charCodeAt(0) - 97;
// Toggle the temp-th bit
mask ^= (1 << temp);
// If a mask is present in the index,
// a palindrome is found from index[mask] to i
if (index.has(mask)) {
answer = Math.max(answer, i - index.get(mask));
} else {
index.set(mask, i);
}
// Check for the palindrome of odd length
for (var j = 0; j < 26; j++) {
var mask2 = mask ^ (1 << j);
if (index.has(mask2)) {
answer = Math.max(answer, i - index.get(mask2));
}
}
}
return answer;
}
// Given String
var s = "adbabd";
// Length of given string
var n = s.length;
// Function call
console.log(longestSubstring(s, n));
Time Complexity: O(N * 26)
Auxiliary Space: O(N * 26)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem