Skip to content

Instantly share code, notes, and snippets.

@sashak007
Created August 3, 2017 04:15
Show Gist options
  • Save sashak007/0ba9c7e65e7320068a4ac30f47567173 to your computer and use it in GitHub Desktop.
Save sashak007/0ba9c7e65e7320068a4ac30f47567173 to your computer and use it in GitHub Desktop.
/**
QUESTION
given an array of strings, determine if the strings can be rearranged
to form a palindrome.
**/
function possiblePalidrome(arr) {
var totalLetters = arr.reduce((total, set) => {
total += set.length;
return total;
}, 0);
var dictionary = {};
var dictionaryKeys = [];
var possible = totalLetters %2 === 0 ? 0 : 1;
var unmatchedLetters = 0;
for(var i = 0; i < arr.length; i++){
for(var j = 0; j < arr[i].length; j++){
if(dictionary[arr[i][j]]) {
dictionary[arr[i][j]]++;
} else {
dictionary[arr[i][j]] = 1;
}
}
}
dictionaryKeys = Object.keys(dictionary);
for(var k = 0; k < dictionaryKeys.length; k++) {
if(unmatchedLetters > possible) {
return false;
}
if(dictionary[dictionaryKeys[k]] % 2 !== 0){
unmatchedLetters++;
}
}
return true;
}
console.log(possiblePalidrome(['aa','abba', 'cc']))
console.log(possiblePalidrome(['aa','abbaw', 'ccc']))
console.log(possiblePalidrome(['a','b','c']))
console.log(possiblePalidrome(['a','abba','cac']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment