Longest substring whose characters can be rearranged to form a Palindrome
Last Updated :
24 Jan, 2023
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++
#include <bits/stdc++.h>
using namespace std;
bool ispalindromic(string s)
{
int n = s.size();
unordered_map< char , int > hashmap;
for ( auto ch : s) {
hashmap[ch]++;
}
int count = 0;
for ( auto i : hashmap) {
if (i.second % 2 == 1)
count++;
}
if (count > 1) {
return false ;
}
return true ;
}
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++) {
curstr += S[j];
if (ispalindromic(curstr)
== true )
{
ans = max(ans, j - i + 1);
}
}
}
return ans;
}
int main()
{
string s = "adbabd" ;
int n = s.size();
cout << (longestSubstring(s, n));
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static boolean ispalindromic(String s)
{
int n = s.length();
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 ;
for (Character i : hashmap.keySet()){
if (hashmap.get(i) % 2 == 1 )
count++;
}
if (count > 1 ) {
return false ;
}
return true ;
}
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++) {
curstr += S.charAt(j);
if (ispalindromic(curstr)
== true )
{
ans = Math.max(ans, j - i + 1 );
}
}
}
return ans;
}
public static void main (String[] args)
{
String s = "adbabd" ;
int n = s.length();
System.out.println(longestSubstring(s, n));
}
}
|
Python3
def ispalindromic(s):
n = len (s)
hashmap = {}
for ch in s:
if (ch in hashmap):
hashmap[ch] = hashmap[ch] + 1
else :
hashmap[ch] = 1
count = 0
for key in hashmap:
if (hashmap[key] % 2 = = 1 ):
count + = 1
if (count > 1 ):
return False
return True
def longestSubstring(S, n):
ans = 0
for i in range ( len (S)):
curstr = ""
for j in range (i, len (S)):
curstr + = S[j]
if (ispalindromic(curstr) = = True ):
ans = max (ans, j - i + 1 )
return ans
s = "adbabd"
n = len (s)
print (longestSubstring(s,n))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static bool ispalindromic( string s)
{
int n = s.Length;
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;
foreach (KeyValuePair< char , int > i in hashmap){
if (i.Value % 2 == 1)
count++;
}
if (count > 1) {
return false ;
}
return true ;
}
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++) {
curstr += S[j];
if (ispalindromic(curstr)
== true )
{
ans = Math.Max(ans, j - i + 1);
}
}
}
return ans;
}
public static void Main()
{
string s = "adbabd" ;
int n = s.Length;
Console.WriteLine(longestSubstring(s, n));
}
}
|
Javascript
function ispalindromic(s) {
let n = s.length;
let hashmap = {};
for (let i = 0; i < n; i++) {
if (!hashmap[s[i]]) {
hashmap[s[i]] = 1;
} else {
hashmap[s[i]]++;
}
}
let count = 0;
for (let key in hashmap) {
if (hashmap[key] % 2 === 1) count++;
}
if (count > 1) {
return false ;
}
return true ;
}
function longestSubstring(S) {
let ans = 0;
for (let i = 0; i < S.length; i++) {
let curstr = "" ;
for (let j = i; j < S.length; j++) {
curstr += S[j];
if (ispalindromic(curstr) === true ) {
ans = Math.max(ans, j - i + 1);
}
}
}
return ans;
}
let s = "adbabd" ;
let n = s.length;
console.log(longestSubstring(s));
|
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++
#include<bits/stdc++.h>
using namespace std;
int longestSubstring(string s, int n)
{
map< int , int > index;
int answer = 0;
int mask = 0;
index[mask] = -1;
for ( int i = 0; i < n; i++)
{
int temp = ( int )s[i] - 97;
mask ^= (1 << temp);
if (index[mask])
{
answer = max(answer,
i - index[mask]);
}
else
index[mask] = i;
for ( int j = 0; j < 26; j++)
{
int mask2 = mask ^ (1 << j);
if (index[mask2])
{
answer =max(answer,
i - index[mask2]);
}
}
}
return answer;
}
int main ()
{
string s = "adbabd" ;
int n = s.size();
cout << (longestSubstring(s, n));
}
|
Java
import java.util.*;
class GFG{
static int longestSubstring(String s, int n)
{
Map<Integer, Integer> index = new HashMap<>();
int answer = 0 ;
int mask = 0 ;
index.put(mask, - 1 );
for ( int i = 0 ; i < n; i++)
{
int temp = ( int )s.charAt(i) - 97 ;
mask ^= ( 1 << temp);
if (index.containsKey(mask))
{
answer = Math.max(answer,
i - index.get(mask));
}
else
index.put(mask,i);
for ( int j = 0 ;j < 26 ; j++)
{
int mask2 = mask ^ ( 1 << j);
if (index.containsKey(mask2))
{
answer = Math.max(answer,
i - index.get(mask2));
}
}
}
return answer;
}
public static void main (String[] args)
{
String s = "adbabd" ;
int n = s.length();
System.out.print(longestSubstring(s, n));
}
}
|
Python3
def longestSubstring(s: str , n: int ):
index = dict ()
answer = 0
mask = 0
index[mask] = - 1
for i in range (n):
temp = ord (s[i]) - 97
mask ^ = ( 1 << temp)
if mask in index.keys():
answer = max (answer,
i - index[mask])
else :
index[mask] = i
for j in range ( 26 ):
mask2 = mask ^ ( 1 << j)
if mask2 in index.keys():
answer = max (answer,
i - index[mask2])
return answer
s = "adbabd"
n = len (s)
print (longestSubstring(s, n))
|
C#
using System.Collections.Generic;
using System;
class GFG{
static int longestSubstring( string s, int n)
{
Dictionary< int ,
int > index = new Dictionary< int ,
int >();
int answer = 0;
int mask = 0;
index[mask] = -1;
for ( int i = 0; i < n; i++)
{
int temp = ( int )s[i] - 97;
mask ^= (1 << temp);
if (index.ContainsKey(mask) == true )
{
answer = Math.Max(answer,
i - index[mask]);
}
else
index[mask] = i;
for ( int j = 0; j < 26; j++)
{
int mask2 = mask ^ (1 << j);
if (index.ContainsKey(mask2) == true )
{
answer = Math.Max(answer,
i - index[mask2]);
}
}
}
return answer;
}
public static void Main ()
{
string s = "adbabd" ;
int n = s.Length;
Console.WriteLine(longestSubstring(s, n));
}
}
|
Javascript
<script>
function longestSubstring(s, n)
{
var index = new Map();
var answer = 0;
var mask = 0;
index[mask] = -1;
for ( var i = 0; i < n; i++)
{
var temp = s[i].charCodeAt(0) - 97;
mask ^= (1 << temp);
if (index[mask])
{
answer = Math.max(answer,
i - index[mask]);
}
else
index[mask] = i;
for ( var j = 0; j < 26; j++)
{
var mask2 = mask ^ (1 << j);
if (index[mask2])
{
answer = Math.max(answer,
i - index[mask2]);
}
}
}
return answer;
}
var s = "adbabd" ;
var n = s.length;
document.write(longestSubstring(s, n));
</script>
|
Time Complexity: O(N * 26)
Auxiliary Space: O(N * 26)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...