Skip to content

Build Palindrome

Given a string, find the shortest possible string which can be achieved by adding characters to the end of initial string to make it a [palindrome]

Example

For st = "abcdc", the output should be

build_palindrome(st) = "abcdcba"

Input/Output

  • [input] string st

    A string consisting of lowercase English letters.

Solution

py
def build_palindrome(st):
    new_str = st
    r_str = ''

    if st == st[::-1]:
        return st

    for c in st:
        r_str = c + r_str
        new_str = st + r_str
        if new_str == new_str[::-1]:
            return new_str

    return new_str


print(build_palindrome('abba'))
js
function build_palindrome(st) {
  let i = 0;
  while (i < st.length) {
    let sub = st.substring(i);
    if (sub === sub.split('').reverse().join('')) {
      return st + st.substring(0, i).split('').reverse().join('');
    }
    i++;
  }
}

console.log(build_palindrome('abba'));

my thoughts are neither my employer's nor my wife's