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.
A set of characters can form a palindrome if at most one character occurs an odd number of times and all characters occur an even number of times.
A simple solution is to run two loops, the outer loop picks all characters one by one, and the inner loop counts the number of occurrences of the picked character. We keep track of odd counts. The time complexity of this solution is O(n2).
We can do it in O(n) time using a count array. Following are detailed steps.
- Create a count array of alphabet size which is typically 256. Initialize all values of the count array as 0.
- Traverse the given string and increment count of every character.
- Traverse the count array and if the count array has more than one odd value, return false. Otherwise, return true.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
#define NO_OF_CHARS 256
bool canFormPalindrome(string str)
{
int count[NO_OF_CHARS] = { 0 };
for ( int i = 0; str[i]; i++)
count[str[i]]++;
int odd = 0;
for ( int i = 0; i < NO_OF_CHARS; i++) {
if (count[i] & 1)
odd++;
if (odd > 1)
return false ;
}
return true ;
}
int main()
{
canFormPalindrome( "geeksforgeeks" )
? cout << "Yes\n"
: cout << "No\n" ;
canFormPalindrome( "geeksogeeks" )
? cout << "Yes\n"
: cout << "No\n" ;
return 0;
}
|
Java
import java.io.*;
import java.math.*;
import java.util.*;
class GFG {
static int NO_OF_CHARS = 256 ;
static boolean canFormPalindrome(String str)
{
int count[] = new int [NO_OF_CHARS];
Arrays.fill(count, 0 );
for ( int i = 0 ; i < str.length(); i++)
count[( int )(str.charAt(i))]++;
int odd = 0 ;
for ( int i = 0 ; i < NO_OF_CHARS; i++) {
if ((count[i] & 1 ) == 1 )
odd++;
if (odd > 1 )
return false ;
}
return true ;
}
public static void main(String args[])
{
if (canFormPalindrome( "geeksforgeeks" ))
System.out.println( "Yes" );
else
System.out.println( "No" );
if (canFormPalindrome( "geeksogeeks" ))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
NO_OF_CHARS = 256
def canFormPalindrome(st):
count = [ 0 ] * (NO_OF_CHARS)
for i in range ( 0 , len (st)):
count[ ord (st[i])] = count[ ord (st[i])] + 1
odd = 0
for i in range ( 0 , NO_OF_CHARS):
if (count[i] & 1 ):
odd = odd + 1
if (odd > 1 ):
return False
return True
if (canFormPalindrome( "geeksforgeeks" )):
print ( "Yes" )
else :
print ( "No" )
if (canFormPalindrome( "geeksogeeks" )):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static int NO_OF_CHARS = 256;
static bool canFormPalindrome( string str)
{
int [] count = new int [NO_OF_CHARS];
Array.Fill(count, 0);
for ( int i = 0; i < str.Length; i++)
count[( int )(str[i])]++;
int odd = 0;
for ( int i = 0; i < NO_OF_CHARS; i++) {
if ((count[i] & 1) == 1)
odd++;
if (odd > 1)
return false ;
}
return true ;
}
public static void Main()
{
if (canFormPalindrome( "geeksforgeeks" ))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
if (canFormPalindrome( "geeksogeeks" ))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
let NO_OF_CHARS = 256;
function canFormPalindrome(str)
{
let count = Array(NO_OF_CHARS).fill(0);
for (let i = 0; i < str.length; i++)
count[str[i].charCodeAt()]++;
let odd = 0;
for (let i = 0; i < NO_OF_CHARS; i++) {
if ((count[i] & 1) == 1)
odd++;
if (odd > 1)
return false ;
}
return true ;
}
if (canFormPalindrome( "geeksforgeeks" ))
document.write( "Yes" );
else
document.write( "No" );
if (canFormPalindrome( "geeksogeeks" ))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string.
Auxiliary Space: O(256), as we are using extra space for the array count.
This article is contributed by Abhishek. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above
Another approach:
We can do it in O(n) time using a list. Following are detailed steps.
- Create a character list.
- Traverse the given string.
- For every character in the string, remove the character if the list already contains else to add to the list.
- If the string length is even the list is expected to be empty.
- Or if the string length is odd the list size is expected to be 1
- On the above two conditions (3) or (4) return true else return false.
C++
#include <bits/stdc++.h>
using namespace std;
bool canFormPalindrome(string str)
{
vector< char > list;
for ( int i = 0; i < str.length(); i++)
{
auto pos = find(list.begin(),
list.end(), str[i]);
if (pos != list.end()) {
auto posi
= find(list.begin(),
list.end(), str[i]);
list.erase(posi);
}
else
list.push_back(str[i]);
}
if (str.length() % 2 == 0
&& list.empty()
|| (str.length() % 2 == 1
&& list.size() == 1))
return true ;
else
return false ;
}
int main()
{
if (canFormPalindrome( "geeksforgeeks" ))
cout << ( "Yes" ) << endl;
else
cout << ( "No" ) << endl;
if (canFormPalindrome( "geeksogeeks" ))
cout << ( "Yes" ) << endl;
else
cout << ( "No" ) << endl;
}
|
Java
import java.util.ArrayList;
import java.util.List;
class GFG {
static boolean canFormPalindrome(String str)
{
List<Character> list = new ArrayList<Character>();
for ( int i = 0 ; i < str.length(); i++)
{
if (list.contains(str.charAt(i)))
list.remove((Character)str.charAt(i));
else
list.add(str.charAt(i));
}
if (str.length() % 2 == 0
&& list.isEmpty()
|| (str.length() % 2 == 1
&& list.size()
== 1 ))
return true ;
else
return false ;
}
public static void main(String args[])
{
if (canFormPalindrome( "geeksforgeeks" ))
System.out.println( "Yes" );
else
System.out.println( "No" );
if (canFormPalindrome( "geeksogeeks" ))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def canFormPalindrome(strr):
listt = []
for i in range ( len (strr)):
if (strr[i] in listt):
listt.remove(strr[i])
else :
listt.append(strr[i])
if ( len (strr) % 2 = = 0 and len (listt) = = 0 or
( len (strr) % 2 = = 1 and len (listt) = = 1 )):
return True
else :
return False
if (canFormPalindrome( "geeksforgeeks" )):
print ( "Yes" )
else :
print ( "No" )
if (canFormPalindrome( "geeksogeeks" )):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG {
static Boolean canFormPalindrome(String str)
{
List< char > list = new List< char >();
for ( int i = 0; i < str.Length; i++)
{
if (list.Contains(str[i]))
list.Remove(( char )str[i]);
else
list.Add(str[i]);
}
if (str.Length % 2 == 0 && list.Count == 0
||
(str.Length % 2 == 1
&& list.Count == 1))
return true ;
else
return false ;
}
public static void Main(String[] args)
{
if (canFormPalindrome( "geeksforgeeks" ))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
if (canFormPalindrome( "geeksogeeks" ))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function canFormPalindrome(str)
{
let list = [];
for (let i = 0; i < str.length; i++)
{
if (list.includes(str[i]))
list.splice(list.indexOf(str[i]), 1);
else
list.push(str[i]);
}
if (str.length % 2 == 0 && list.length == 0 ||
(str.length % 2 == 1 && list.length == 1))
return true ;
else
return false ;
}
if (canFormPalindrome( "geeksforgeeks" ))
document.write( "Yes<br>" );
else
document.write( "No<br>" );
if (canFormPalindrome( "geeksogeeks" ))
document.write( "Yes<br>" );
else
document.write( "No<br>" );
</script>
|
Time Complexity: O(N*N), as we are using a loop to traverse N times and in each traversal, we are using the find function to get the position of a character which will cost O(N) time. Where N is the length of the string.
Auxiliary Space: O(N), as we are using extra space for the array of characters list. Where N is the length of the string.
Another Approach: (Using Bits)
This problem can be solved in O(n) time where n is the number of characters in the string and O(1) space.
The string to be palindrome all the characters should occur an even number of times if the string is of even length and at most one character can occur an odd number of times if the string length is odd. Track of the count of the characters is not required instead, it is sufficient to keep track if the counts are odd or even.
This can be achieved by using a variable as a bit vector.
For every character in the string:
if the bit corresponding to the character is not set: //if it is the character’s odd occurrence set the bit
else if the bit corresponding to the character is set: //if it is the character’s even occurrence toggle the bit
This is similar to performing an XOR operation between bit vector and mask.
Below is the implementation of the above approach:
C++
# include <bits/stdc++.h>
using namespace std;
bool canFormPalindrome(string a)
{
int bitvector = 0, mask = 0;
for ( int i=0; a[i] != '\0' ; i++)
{
int x = a[i] - 'a' ;
mask = 1 << x;
bitvector = bitvector ^ mask;
}
return (bitvector & (bitvector - 1)) == 0;
}
int main()
{
if (canFormPalindrome( "geeksforgeeks" ))
cout << ( "Yes" ) << endl;
else
cout << ( "No" ) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static boolean canFormPalindrome(String a)
{
int bitvector = 0 , mask = 0 ;
for ( int i = 0 ; i < a.length(); i++)
{
int x = a.charAt(i) - 'a' ;
mask = 1 << x;
bitvector = bitvector ^ mask;
}
return (bitvector & (bitvector - 1 )) == 0 ;
}
public static void main (String[] args) {
if (canFormPalindrome( "geeksforgeeks" ))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def canFormPalindrome(s):
bitvector = 0
for str in s:
bitvector ^ = 1 << ord ( str )
return bitvector = = 0 or bitvector & (bitvector - 1 ) = = 0
if canFormPalindrome( "geeksforgeeks" ):
print ( 'Yes' )
else :
print ( 'No' )
|
C#
using System;
public class GFG
{
static bool canFormPalindrome( string a)
{
int bitvector = 0, mask = 0;
for ( int i = 0; i < a.Length; i++)
{
int x = a[i] - 'a' ;
mask = 1 << x;
bitvector = bitvector ^ mask;
}
return (bitvector & (bitvector - 1)) == 0;
}
static public void Main (){
if (canFormPalindrome( "geeksforgeeks" ))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function canFormPalindrome(a)
{
var bitvector = 0, mask = 0;
for ( var i = 0; i < a.length; i++)
{
var x = a.charCodeAt(i) - 97;
mask = 1 << x;
bitvector = bitvector ^ mask;
}
return ((bitvector & (bitvector - 1)) == 0);
}
if (canFormPalindrome( "geeksforgeeks" ))
document.write( "Yes" + "<br>" );
else
document.write( "No" + "<br>" );
</script>
|
Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string.
Auxiliary Space: O(1), as we are not using any extra space.