Skip to main content

Shortest Palindrome

Problem statement

You are given a string s. You can convert s to a palindrome by adding characters in front of it.

Return the shortest palindrome you can find by performing this transformation.

Example 1:

Input: s = "aacecaaa"Output: "aaacecaaa"

Example 2:

Input: s = "abcd"Output: "dcbabcd"

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of lowercase English letters only.

My solution

/**
* @param {string} s
* @return {string}
*/
var shortestPalindrome = function(s) {
const reverse = s.split("").reverse().join("");
let subStr = "";

for (let i = s.length - 1; i >= 0; i--) {
const index = i + 1;

// console.log(reverse.slice(s.length - index, s.length), s.slice(0, index), reverse.slice(index), index)
if (reverse.slice(s.length - index, s.length) === s.slice(0, index)) {
subStr = reverse.slice(0, s.length - index)
break;
}
}

// console.log(subStr)

return subStr + s
};