0

Leetcode Description

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 and right initialized to the start and the end characters of the string, respectively, keep incrementing left and decrementing right synchronously as long as the two characters pointed by left and right are equal.

The first time we run into a mismatch between the characters pointed by left and right, and say these are specifically indices i and j, we simply check whether string[i..j-1] or string[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?

Community
  • 1
  • 1
namesake22
  • 345
  • 2
  • 12
  • If you want to prove it is incorrect then simply produce a string which it gives the wrong result for, or for which it doesn't terminate. If there is no such string then it is correct, by definition. – kaya3 Nov 21 '19 at 18:40
  • @kaya3 i think proving there is no such string is even harder? – namesake22 Nov 23 '19 at 00:50
  • Well, yes, since you can't prove it correct by just exhibiting one example. But I suspect that if a counterexample exists, then it shouldn't be too hard to find - so if you think the algorithm is incorrect, try constructing a counterexample. If you aren't able to, at least you'll have gained some insight that might help you prove it correct. – kaya3 Nov 23 '19 at 00:53

0 Answers0