2

I was asked this question in an interview:

Given a string (1<=|s|<=10^5), check if it is possible to partition it into three palindromes. If there are multiple answers possible, output the one where the cuts are made the earliest. If no answer is possible, print "Impossible".

**Input:**

radarnoonlevel

aabab

abcdefg

**Output:**

radar noon level

a a bab   (Notice how a, aba, b is also an answer, but we will output the one with the earliest cuts)

Impossible

I was able to give a brute force solution, running two loops and checking palindrome property for every 3 substrings ( 0-i, i-j, j-end). This was obviously not optimal, but I have not been able to find a better solution since then.

I need a way of checking that if I know the palindrome property of a string, then how removing a character from the start or adding one at the end can give me the property of the new string without having to do the check for the whole string again. I am thinking of using three maps where each character key is mapped to number of occurences but that too doesn't lead me down anything.

Nikhil_10
  • 133
  • 3
  • 10

1 Answers1

1

Still O(n^2) solution, but you can store the result of palindrome substrings in a table and use that to get to the answer.

vector<string> threePalindromicSubstrings(string word) {
    int n = word.size();
    vector<vector<bool>> dp (n,vector<bool>(n,false));
    for(int i = 0 ; i < n ; ++i)
        dp[i][i] = 1;
    
    for(int l = 2 ; l <= n ; ++l){
        for(int i = 0 ; i < n - l +1 ; ++i){
            int j = i + l - 1;
            if(l == 2)
                dp[i][j] = (word[i] == word[j]);
            else
                dp[i][j] = (word[i] == word[j]) && (dp[i+1][j-1]);
        }
    }

    vector<string> ans;
    for(int i = 0 ; i < n - 2 ; ++i){
        if(dp[0][i]) {
            for(int j = i+1 ; j < n - 1 ; ++j){
                if(dp[i+1][j] && dp[j+1][n-1]){
                    ans.push_back(word.substr(0,i + 1));
                    ans.push_back(word.substr(i+1,j-i));
                    ans.push_back(word.substr(j+1,n-j));
                    return ans;
                }
            }
        }
    }
    if(ans.empty())
        ans.push_back("Impossible");
    return ans;
}