KatInterview

214. Shortest Palindrome

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the shortest palindrome by adding characters only to the beginning of a given string s.

Solution

Shortest Palindrome in Python

class Solution:
    def shortestPalindrome(self, s: str) -> str:
        n = len(s)
        if n == 0:
            return ""

        # Create the reversed string
        rev_s = s[::-1]

        # Construct the temporary string for KMP's LPS computation
        # temp = s + '#' + rev_s
        temp = s + '#' + rev_s
        temp_n = len(temp)

        # Compute the LPS (Longest Proper Prefix which is also Suffix) array
        lps = [0] * temp_n
        # length of the previous longest prefix suffix
        length = 0
        i = 1
        while i < temp_n:
            if temp[i] == temp[length]:
                length += 1
                lps[i] = length
                i += 1
            else:
                if length != 0:
                    length = lps[length - 1]
                else:
                    lps[i] = 0
                    i += 1

        # The length of the longest palindromic prefix of s is given by lps[-1]
        palindrome_prefix_len = lps[-1]

        # The suffix of s that is not part of the palindrome
        suffix_to_add = s[palindrome_prefix_len:]

        # Reverse this suffix and prepend it to the original string s
        return suffix_to_add[::-1] + s

Shortest Palindrome in Java

class Solution {
    public String shortestPalindrome(String s) {
        int n = s.length();
        if (n == 0) {
            return "";
        }

        // Create the reversed string
        String rev_s = new StringBuilder(s).reverse().toString();

        // Construct the temporary string for KMP's LPS computation
        // temp = s + '#' + rev_s
        String temp = s + "#" + rev_s;
        int temp_n = temp.length();

        // Compute the LPS (Longest Proper Prefix which is also Suffix) array
        int[] lps = new int[temp_n];
        // length of the previous longest prefix suffix
        int length = 0;
        int i = 1;
        while (i < temp_n) {
            if (temp.charAt(i) == temp.charAt(length)) {
                length++;
                lps[i] = length;
                i++;
            } else {
                if (length != 0) {
                    length = lps[length - 1];
                } else {
                    lps[i] = 0;
                    i++;
                }
            }
        }

        // The length of the longest palindromic prefix of s is given by lps[temp_n - 1]
        int palindromePrefixLen = lps[temp_n - 1];

        // The suffix of s that is not part of the palindrome
        String suffixToAdd = s.substring(palindromePrefixLen);

        // Reverse this suffix and prepend it to the original string s
        return new StringBuilder(suffixToAdd).reverse().toString() + s;
    }
}

Shortest Palindrome in C++

class Solution {
public:
    string shortestPalindrome(string s) {
        int n = s.length();
        if (n == 0) {
            return "";
        }

        // Create the reversed string
        string rev_s = s;
        reverse(rev_s.begin(), rev_s.end());

        // Construct the temporary string for KMP's LPS computation
        // temp = s + '#' + rev_s
        string temp = s + "#" + rev_s;
        int temp_n = temp.length();

        // Compute the LPS (Longest Proper Prefix which is also Suffix) array
        vector<int> lps(temp_n, 0);
        // length of the previous longest prefix suffix
        int length = 0;
        int i = 1;
        while (i < temp_n) {
            if (temp[i] == temp[length]) {
                length++;
                lps[i] = length;
                i++;
            } else {
                if (length != 0) {
                    length = lps[length - 1];
                } else {
                    lps[i] = 0;
                    i++;
                }
            }
        }

        // The length of the longest palindromic prefix of s is given by lps[temp_n - 1]
        int palindrome_prefix_len = lps[temp_n - 1];

        // The suffix of s that is not part of the palindrome
        string suffix_to_add = s.substr(palindrome_prefix_len);

        // Reverse this suffix
        reverse(suffix_to_add.begin(), suffix_to_add.end());

        // Prepend the reversed suffix to the original string s
        return suffix_to_add + s;
    }
};

Shortest Palindrome in TypeScript

function shortestPalindrome(s: string): string {
    const n = s.length;
    if (n === 0) {
        return "";
    }

    // Create the reversed string
    const rev_s = s.split('').reverse().join('');

    // Construct the temporary string for KMP's LPS computation
    // temp = s + '#' + rev_s
    const temp = s + "#" + rev_s;
    const temp_n = temp.length;

    // Compute the LPS (Longest Proper Prefix which is also Suffix) array
    const lps: number[] = new Array(temp_n).fill(0);
    // length of the previous longest prefix suffix
    let length = 0;
    let i = 1;
    while (i < temp_n) {
        if (temp[i] === temp[length]) {
            length++;
            lps[i] = length;
            i++;
        } else {
            if (length !== 0) {
                length = lps[length - 1];
            } else {
                lps[i] = 0;
                i++;
            }
        }
    }

    // The length of the longest palindromic prefix of s is given by lps[temp_n - 1]
    const palindromePrefixLen = lps[temp_n - 1];

    // The suffix of s that is not part of the palindrome
    const suffixToAdd = s.substring(palindromePrefixLen);

    // Reverse this suffix and prepend it to the original string s
    return suffixToAdd.split('').reverse().join('') + s;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.