Given an anagram string S of length N, the task is to check whether it can be made palindrome or not.
Examples:
Input : S = geeksforgeeks
Output: No
Explanation: There is no palindrome anagram of given string
Input: S = geeksgeeks
Output: Yes
Explanation: There are palindrome anagrams of given string. For example kgeesseegk
This problem is basically the same as Check if characters of a given string can be rearranged to form a palindrome.
Check if any anagram of a string is palindrome or not by counting frequency of each characters:
- Create a count[] of alphabet size which is typically 256, for storing the frequency of each characters.
- Traverse the given string and increment count of every character in count[].
- Traverse the count array and if the count array has more than one odd values, return false. Otherwise, return true.
Below is the implementation of the above approach:
C++
#include <iostream>
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
public class GFG {
static final int NO_OF_CHARS = 256 ;
static boolean canFormPalindrome(String str)
{
int [] count = new int [NO_OF_CHARS];
for ( int i = 0 ; i < str.length(); i++)
count[str.charAt(i)]++;
int odd = 0 ;
for ( int i = 0 ; i < NO_OF_CHARS; i++) {
if ((count[i] & 1 ) != 0 )
odd++;
if (odd > 1 )
return false ;
}
return true ;
}
public static void main(String args[])
{
System.out.println(canFormPalindrome( "geeksforgeeks" )
? "Yes"
: "No" );
System.out.println(canFormPalindrome( "geeksogeeks" )
? "Yes"
: "No" );
}
}
|
Python
NO_OF_CHARS = 256
def canFormPalindrome(string):
count = [ 0 for i in range (NO_OF_CHARS)]
for i in string:
count[ ord (i)] + = 1
odd = 0
for i in range (NO_OF_CHARS):
if (count[i] & 1 ):
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;
public class GFG {
static int NO_OF_CHARS = 256;
static bool canFormPalindrome( string str)
{
int [] count = new int [NO_OF_CHARS];
for ( int i = 0; i < str.Length; i++)
count[str[i]]++;
int odd = 0;
for ( int i = 0; i < NO_OF_CHARS; i++) {
if ((count[i] & 1) != 0)
odd++;
if (odd > 1)
return false ;
}
return true ;
}
public static void Main()
{
Console.WriteLine(
canFormPalindrome( "geeksforgeeks" )
? "Yes" : "No" );
Console.WriteLine(
canFormPalindrome( "geeksogeeks" )
? "Yes" : "No" );
}
}
|
Javascript
<script>
let NO_OF_CHARS = 256;
function canFormPalindrome(str)
{
let count = new Array(NO_OF_CHARS);
count.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) != 0)
odd++;
if (odd > 1)
return false ;
}
return true ;
}
document.write(canFormPalindrome( "geeksforgeeks" )? "Yes" + "</br>" : "No" + "</br>" );
document.write(canFormPalindrome( "geeksogeeks" )? "Yes" : "No" );
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1) because using constant (~256) space
Check if any anagram of a string is palindrome or not by counting frequency of each characters in HashMap:
Below is the implementation:
C++
#include <iostream>
#include <unordered_map> //header file for unordered_map
using namespace std;
bool isPossible(string S)
{
unordered_map< char , int >
a;
for ( char c : S) {
a++;
}
int c = 0;
for ( auto v : a) {
if (v.second % 2
== 1) {
c++;
}
}
if (c > 1) {
return false ;
}
return true ;
}
int main()
{
bool q = isPossible( "geeksogeeks" );
cout << boolalpha << q
<< endl;
bool z = isPossible( "geeksforgeeks" );
cout << boolalpha << z
<< endl;
return 0;
}
|
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static boolean isPossible(String S)
{
Map<Character, Integer> a = new HashMap<>();
for ( char c : S.toCharArray()) {
a.put(c, a.getOrDefault(c, 0 ) + 1 );
}
int c = 0 ;
for ( int v : a.values()) {
if (v % 2
== 1 ) {
c++;
}
}
if (c > 1 ) {
return false ;
}
return true ;
}
public static void main(String[] args)
{
boolean q = isPossible( "geeksogeeks" );
System.out.println(
boolalpha(q));
boolean z = isPossible( "geeksforgeeks" );
System.out.println(
boolalpha(z));
}
public static String boolalpha( boolean b)
{
return b ? "True" : "False" ;
}
}
|
Python3
from collections import Counter
def isPossible(S):
a = Counter(S)
a = dict (a)
c = 0
for v in a.values():
if v % 2 = = 1 :
c + = 1
if c> 1 :
return False
return True
q = isPossible( 'geeksogeeks' )
print (q)
z = isPossible( 'geeksforgeeks' )
print (z)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static bool IsPossible( string s)
{
Dictionary< char , int > a
= new Dictionary< char , int >();
foreach ( char c in s)
{
if (a.ContainsKey(c)) {
a++;
}
else {
a.Add(c, 1);
}
}
int count = 0;
foreach ( int v in a.Values)
{
if (v % 2 == 1) {
count++;
}
}
if (count > 1) {
return false ;
}
return true ;
}
static void Main( string [] args)
{
bool q = IsPossible( "geeksogeeks" );
Console.WriteLine(q);
bool z = IsPossible( "geeksforgeeks" );
Console.WriteLine(z);
}
}
|
Javascript
function isPossible(S) {
const a = {};
for (let i = 0; i < S.length; i++) {
if (S[i] in a) {
a[S[i]]++;
} else {
a[S[i]] = 1;
}
}
let c = 0;
for (const v of Object.values(a)) {
if (v % 2 === 1) {
c++;
}
}
if (c > 1) {
return false ;
}
return true ;
}
const q = isPossible( 'geeksogeeks' );
console.log(q);
const z = isPossible( 'geeksforgeeks' );
console.log(z);
|
Time Complexity: O(n) where n is size of string
Auxiliary Space: O(n) because every character of the string in added in the map which inturn is the length of string.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!