Given a string of length n
, you have to decide whether the string is a palindrome or not, but you may delete at most one character.
For example: "aba" is a palindrome.
"abca" is also valid, since we may remove either "b" or "c" to get a palindrome.
I have seen many solutions that take the following approach.
With two pointers
left
andright
initialized to the start and the end characters of the string, respectively, keep incrementingleft
and decrementingright
synchronously as long as the two characters pointed byleft
andright
are equal.The first time we run into a mismatch between the characters pointed by
left
andright
, and say these are specifically indicesi
andj
, we simply check whetherstring[i..j-1]
orstring[i+1..j]
is a palindrome.
I clearly see why this works, but one thing that's bothering me is the direction of the approach that we take when we first see the mismatch.
Assuming we do not care about time efficiency and only focus on correctness, I cannot see what prevents us from trying to delete a character in string[0..i-1]
or string[j+1..n-1]
and try to look whether the entire resulting string can become a palindrome or not?
More specifically, if we take the first approach and see that both string[i..j-1]
and string[i+1..j]
are not palindromes, what prevents us from backtracking to the second approach I described and see if deleting a character from string[0..i-1]
or string[j+1..n-1]
will yield a palindrome instead?
Can we mathematically prove why this approach is useless or simply incorrect?