[Code] Check if characters of a given string can be rearranged to form a palindrome

August 31, 2015


Today is a last day of August, time goes fast. And again, last saturday, my company has had a Code Challenge day, all of 6 problems are quite simple, and almost of us finished them before time was up. But, there is a problem that I can see it is quite interesting. This took a bit time more than others. As a title we can see, we will solve this, but first, let’s me give you some introduction about Palindrome is.

What is Palindrome?

You can find and understand it easily in this link, so that, for example of Palindrome: “abccba”, “abbyuybba”, “abba” …

But “abc”, “abccca” … are not Palindrome, that is quite simple right?


So how to check if a characters or string can be formed a Palindrome. I have came up with my own solution for this, in Objective-C.

int oddCount = 0;
for(int i = 0; i < string.length; i++){
int numberOfChar = 1;
for(int j = 0; j < string.length; j++){

// check a char at i is the same with a char at j
// if right, so numberOfChar++

if([[string substringWithRange:NSMakeRange(i, 1)] isEqualToString:[string substringWithRange:NSMakeRange(j, 1)]] && i != j){
// check if numberOfChar is odd, it means that number of chars in string is odd.

if(numberOfChar % 2 == 1){

// we can only accept one odd char, it is in middle of string
return oddCount <= 1;

That’s it.

So, we can see that problems releated to Palindrome are quite interesting.

If you have anything to contribute or ask, all your comments will be welcomed. Thanks for reading my post.

Update …

This is additional problem, this solve problem check given string is Palindrome or not by using Objective-C. Here is a snippet code I offen use.


NSInteger length = str.length;
NSInteger halfLength = length / 2;
__block BOOL isPalindrome = YES;

[str enumerateSubstringsInRange:NSMakeRange(0, halfLength) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
NSRange otherRange = [str rangeOfComposedCharacterSequenceAtIndex:length - enclosingRange.location - 1];

if (![substring isEqualToString:[str substringWithRange:otherRange]]) {
isPalindrome = NO;
*stop = YES;

return isPalindrome;