This questions is a variation of Longest Common Subsequence.
We know that longest palindrome of a string can be found by finding the lcs of string and reverse of string
Now after lcs is found, the remaining elements of input string will be the one not part of the palindrome. They are the ones whose duplicates are missing so they need to be added.
Eg: abca
Longest palindrome: aa
Remaining elements: bc
So elements to be added b & c
As we only need to return the numbers, we can find length of lps(lcs of string and reversed string) and subtract it from the length of the string.
In above example lps = 2 and string len = 4
Ans = 4 - 2 = 2
//function to find length of longest common subsequence
int LCS(string &x, string &y, int n, int m){
vector<vector<int>> t(n+1, vector<int>(m+1));
for(int i = 0; i<n+1; i++){
for(int j = 0; j<m+1; j++){
if(i==0 || j == 0){
t[i][j] = 0;
}
}
}
for(int i = 1; i<n+1; i++){
for(int j = 1; j<m+1; j++){
if(x[i-1]==y[j-1]){
t[i][j] = 1 + t[i-1][j-1];
}
else{
t[i][j] = max(t[i-1][j],t[i][j-1]);
}
}
}
return t[n][m];
}
//using string and reverse of string to find lcs helps find longest palindrome
//now elements remaining from longest palindrome in lcs can be deleted to make input string palindrom
//or their copy can be added to input string to make palindrome
int minimumInsertions(string &str)
{
// Write your code here.
string r = str;
reverse(str.begin(), str.end());
int n = str.length();
int x = LCS(str,r, n, n);
return str.length() - x;
}
Hope it helps!