Last active
December 22, 2015 03:23
-
-
Save akhoury/d80344be4082ccc050a9 to your computer and use it in GitHub Desktop.
palindromize a word if possible in O(n), if already a palindrom return it, otherwise return null
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function palindromize(word) { | |
if (Array.isArray(word)) { | |
return word.map(palindromize); | |
}; | |
if (!word) return null; | |
word = "" + word; | |
// single letter words? really? i don't know.. | |
if (word.length === 1) return word; | |
var hash = {}; | |
var half = Math.floor(word.length / 2); | |
var isPalindrom = true; | |
for (var i = 0; i < word.length; i++) { | |
hash[word[i]] = hash[word[i]] || 0; | |
hash[word[i]]++; | |
// since we're iterating, mind as well check if it's already a palindrom | |
if (i < half && isPalindrom && word[i] !== word[word.length - 1 - i]) { | |
isPalindrom = false; | |
} | |
} | |
if (isPalindrom) return word; | |
var letters = Object.keys(hash); | |
var oddLetter; | |
var left = ""; | |
var right = ""; | |
letters.every(function(letter) { | |
var count = hash[letter]; | |
if (count % 2 !== 0) { | |
if (oddLetter) { | |
left = ""; | |
return false; | |
} | |
oddLetter = letter; | |
count--; | |
} | |
var add = Array(count / 2 + 1).join(letter); | |
left = add + left; | |
right += add; | |
return true; | |
}); | |
return left ? left + (oddLetter || "") + right : null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment