Given a string, Check if 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 odd number of times and all characters occur even number of times.
A simple solution is to run two loops, the outer loop picks all characters one by one, the inner loop counts number of occurrences of the picked character. We keep track of odd counts. Time complexity of this solution is O(n2).
We can do it in O(n) time using a count array. Following are detailed steps.
1) Create a count array of alphabet size which is typically 256. Initialize all values of count array as 0.
2) Traverse the given string and increment count of every character.
3) 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 above approach.
C++
// C++ implementation to check if // characters of a given string can // be rearranged to form a palindrome #include<bits/stdc++.h> using namespace std; #define NO_OF_CHARS 256 /* function to check whether characters of a string can form a palindrome */bool canFormPalindrome(string str) { // Create a count array and initialize all // values as 0 int count[NO_OF_CHARS] = {0}; // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; str[i]; i++) count[str[i]]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if (count[i] & 1) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true; } /* Driver program*/int main() { canFormPalindrome("geeksforgeeks")? cout << "Yes\n": cout << "No\n"; canFormPalindrome("geeksogeeks")? cout << "Yes\n": cout << "No\n"; return 0; } |
Java
// Java implementation to check if // characters of a given string can // be rearranged to form a palindrome import java.io.*; import java.util.*; import java.math.*; class GFG { static int NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ static boolean canFormPalindrome(String str) { // Create a count array and initialize all // values as 0 int count[] = new int[NO_OF_CHARS]; Arrays.fill(count, 0); // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; i < str.length(); i++) count[(int)(str.charAt(i))]++; // Count odd occurring characters 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 if odd count is 0 or 1, return true; } // Driver program 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"); } } // This code is contributed by Nikita Tiwari. |
Python3
# Python3 implementation to check if # characters of a given string can # be rearranged to form a palindrome NO_OF_CHARS = 256 # function to check whether characters # of a string can form a palindrome def canFormPalindrome(st) : # Create a count array and initialize # all values as 0 count = [0] * (NO_OF_CHARS) # For each character in input strings, # increment count in the corresponding # count array for i in range( 0, len(st)) : count[ord(st[i])] = count[ord(st[i])] + 1 # Count odd occurring characters 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 odd count is 0 or 1, return True # Driver program if(canFormPalindrome("geeksforgeeks")) : print("Yes") else : print("No") if(canFormPalindrome("geeksogeeks")) : print("Yes") else : print("No") # This code is contributed by Nikita Tiwari. |
C#
// C# implementation to check if // characters of a given string can // be rearranged to form a palindrome using System; class GFG { static int NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ static bool canFormPalindrome(string str) { // Create a count array and initialize all // values as 0 int[] count = new int[NO_OF_CHARS]; Array.Fill(count, 0); // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; i < str.Length; i++) count[(int)(str[i])]++; // Count odd occurring characters 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 if odd count is 0 or 1, return true; } // Driver program public static void Main() { if (canFormPalindrome("geeksforgeeks")) Console.WriteLine("Yes"); else Console.WriteLine("No"); if (canFormPalindrome("geeksogeeks")) Console.WriteLine("Yes"); else Console.WriteLine("No"); } } |
Output:
No Yes
This article is contributed by Abhishek. Please write comments if you find anything incorrect, or 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.
1) Create a character list.
2) Traverse the given string.
3) For every character in the string, remove the character if the list already contains else add to the list.
3) If the string length is even the list is expected to be empty.
4) Or if the string length is odd the list size is expected to be 1
5) On the above two conditions (3) or (4) return true else return false.
C++
#include<bits/stdc++.h> using namespace std; /* * function to check whether characters of a string can form a palindrome */bool canFormPalindrome(string str) { // Create a list vector<char> list; // For each character in input strings, // remove character if list contains // else add character to 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 character length is even list is expected to be empty // or if character length is odd list size is expected to be 1 if (str.length() % 2 == 0 && list.empty() // if string length is even || (str.length() % 2 == 1 && list.size() == 1)) // if string length is odd return true; else return false; } // Driver program int main() { if (canFormPalindrome("geeksforgeeks")) cout << ("Yes") << endl; else cout << ("No") << endl; if (canFormPalindrome("geeksogeeks")) cout << ("Yes") << endl; else cout << ("No") << endl; } // This code is contributed by Rajput-Ji |
Java
import java.util.ArrayList; import java.util.List; class GFG{ /* * function to check whether characters of a string can form a palindrome */ static boolean canFormPalindrome(String str) { // Create a list List<Character> list = new ArrayList<Character>(); // For each character in input strings, // remove character if list contains // else add character to list 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 character length is even list is expected to be empty // or if character length is odd list size is expected to be 1 if (str.length() % 2 == 0 && list.isEmpty() // if string length is even || (str.length() % 2 == 1 && list.size() == 1)) // if string length is odd return true; else return false; } // Driver program 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"); } } // This code is contributed by Sugunakumar P |
Python3
''' * function to check whether characters of a strring can form a palindrome '''def canFormPalindrome(strr): # Create a listt listt = [] # For each character in input strrings, # remove character if listt contains # else add character to listt for i in range(len(strr)): if (strr[i] in listt): listt.remove(strr[i]) else: listt.append(strr[i]) # if character length is even listt is expected to be empty # or if character length is odd listt size is expected to be 1 if (len(strr)% 2 == 0 and len(listt) == 0 or \ (len(strr) % 2 == 1 and len(listt) == 1)): return True else: return False # Driver code if (canFormPalindrome("geeksforgeeks")): print("Yes") else: print("No") if (canFormPalindrome("geeksogeeks")): print("Yes") else: print("No") # This code is contributed by SHUBHAMSINGH10 |
C#
// C# Implementation of the above approach using System; using System.Collections.Generic; class GFG { /* * function to check whether characters of a string can form a palindrome */ static Boolean canFormPalindrome(String str) { // Create a list List<char> list = new List<char>(); // For each character in input strings, // remove character if list contains // else add character to list for (int i = 0; i < str.Length; i++) { if (list.Contains(str[i])) list.Remove((char) str[i]); else list.Add(str[i]); } // if character length is even // list is expected to be empty // or if character length is odd // list size is expected to be 1 if (str.Length % 2 == 0 && list.Count == 0 || // if string length is even (str.Length % 2 == 1 && list.Count == 1)) // if string length is odd return true; else return false; } // Driver Code 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"); } } // This code is contributed by Rajput-Ji |
Output:
No Yes
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Longest substring whose characters can be rearranged to form a Palindrome
- Check if a string can be rearranged to form special palindrome
- Check if characters of each word can be rearranged to form an Arithmetic Progression (AP)
- Find the count of sub-strings whose characters can be rearranged to form the given word
- Check if string can be rearranged so that every Odd length Substring is Palindrome
- Minimum length of the sub-string whose characters can be used to form a palindrome of length K
- Check if the characters in a string form a Palindrome in O(1) extra space
- Check if characters of a given string can be used to form any N equal strings
- Check if characters of one string can be swapped to form other
- Check if string remains palindrome after removing given number of characters
- Rearrange characters to form palindrome if possible
- Maximum length palindrome that can be created with characters in range L and R
- Check whether second string can be formed from characters of first string
- Generate a string whose all K-size substrings can be concatenated to form the given string
- Minimum number of characters to be replaced to make a given string Palindrome
- Minimum removal of characters required such that permutation of given string is a palindrome
- Check if a string can be converted to another by swapping of adjacent characters of given type
- Check if a given string can be formed using characters of adjacent cells of a Matrix
- Check if permutation of a given string can be made palindromic by removing at most K characters
- Minimal moves to form a string by adding characters or appending string itself

