Check if characters of a given string can be rearranged to form a palindrome
Last Updated :
23 Jul, 2025
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++
// 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 code*/
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.math.*;
import java.util.*;
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 code
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 code
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 code
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>
// Javascript implementation to check if
// characters of a given string can
// be rearranged to form a palindrome
let NO_OF_CHARS = 256;
/* function to check whether characters
of a string can form a palindrome */
function canFormPalindrome(str)
{
// Create a count array and initialize all
// values as 0
let count = Array(NO_OF_CHARS).fill(0);
// For each character in input strings,
// increment count in the corresponding
// count array
for (let i = 0; i < str.length; i++)
count[str[i].charCodeAt()]++;
// Count odd occurring characters
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 odd count is 0 or 1,
return true;
}
// Driver program
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.
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;
/*
* 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 string length is even
if (str.length() % 2 == 0
&& list.empty()
|| (str.length() % 2 == 1
&& list.size() == 1))
return true;
// if string length is odd
else
return false;
}
// Driver code
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 string length is even
if (str.length() % 2 == 0
&& list.isEmpty()
|| (str.length() % 2 == 1
&& list.size()
== 1))
return true;
// if string length is odd
else
return false;
}
// Driver code
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 string can form a palindrome
'''
def canFormPalindrome(strr):
# Create a list
listt = []
# For each character in input strings,
# remove character if list contains
# else add character to list
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
# list is expected to be empty
# or if character length is odd
# list 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 string length is even
if (str.Length % 2 == 0 && list.Count == 0
||
(str.Length % 2 == 1
&& list.Count == 1))
return true;
// if string length is odd
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
JavaScript
<script>
/*
* function to check whether
* characters of a string can form a palindrome
*/
function canFormPalindrome(str)
{
// Create a list
let list = [];
// For each character in input strings,
// remove character if list contains
// else add character to 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 character length is even
// list is expected to be empty or
// if character length is odd list size
// is expected to be 1
// If string length is even
if (str.length % 2 == 0 && list.length == 0 ||
(str.length % 2 == 1 && list.length == 1))
return true;
// If string length is odd
else
return false;
}
// Driver code
if (canFormPalindrome("geeksforgeeks"))
document.write("Yes<br>");
else
document.write("No<br>");
if (canFormPalindrome("geeksogeeks"))
document.write("Yes<br>");
else
document.write("No<br>");
// This code is contributed by ab2127
</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++
// C++ Implementation of the above approach
# include <bits/stdc++.h>
using namespace std;
bool canFormPalindrome(string a)
{
// bitvector to store
// the record of which character appear
// odd and even number of times
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;
}
// Driver Code
int main()
{
if (canFormPalindrome("geeksforgeeks"))
cout << ("Yes") << endl;
else
cout << ("No") << endl;
return 0;
}
Java
// Java Implementation of the above approach
import java.io.*;
class GFG
{
static boolean canFormPalindrome(String a)
{
// bitvector to store
// the record of which character appear
// odd and even number of times
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;
}
// Driver Code
public static void main (String[] args) {
if (canFormPalindrome("geeksforgeeks"))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by rag2127
Python3
# Python3 implementation of above approach.
def canFormPalindrome(s):
bitvector = 0
for str in s:
bitvector ^= 1 << ord(str)
return bitvector == 0 or bitvector & (bitvector - 1) == 0
#s = input()
if canFormPalindrome("geeksforgeeks"):
print('Yes')
else:
print('No')
# This code is contributed by sahilmahale0
C#
// C# Implementation of the above approach
using System;
public class GFG
{
static bool canFormPalindrome(string a)
{
// bitvector to store
// the record of which character appear
// odd and even number of times
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;
}
// Driver Code
static public void Main (){
if (canFormPalindrome("geeksforgeeks"))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by avanitrachhadiya2155
JavaScript
<script>
// JavaScript implementation of the above approach
function canFormPalindrome(a)
{
// Bitvector to store the record
// of which character appear
// odd and even number of times
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);
}
// Driver Code
if (canFormPalindrome("geeksforgeeks"))
document.write("Yes" + "<br>");
else
document.write("No" + "<br>");
// This code is contributed by akshitsaxenaa09
</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.
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