Palindrome Index

See the original problem on HackerRank.

Solutions

If the string is already a palindrome, -1 is the answer since no character need be removed.

If the given string is not a palindrome, we must find one character that, once removed, will make it a palindrome. We can do this by checking if str[i] == str[N - 1 - i] where N is the length of the string for all i starting from i=0. Once this condition fails, all we have to do is to check if str[0:i-1] + str[i+1:N-1] is a palindrome. If it is a palindrome, we print the value of i; otherwise, we print the value of N-i-1.

Possible C++ implementation:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22  size_t T; string S; cin >> T; while (T--) { cin >> S; const auto mid = begin(S) + S.size()/2; const auto diffIt = mismatch(begin(S), mid, S.rbegin()).first; if (diffIt != begin(S) + S.size()/2) { const auto diffIdx = distance(begin(S), diffIt); if (equal(begin(S), diffIt, S.rbegin()) && equal(next(diffIt), mid, S.rbegin() + diffIdx)) cout << diffIdx << endl; else cout << S.size() - diffIdx - 1 << endl; } else { cout << -1 << endl; } } 
We've worked on this challenge in these gyms: modena