Valid Palindrome II
Decide whether deleting at most one character can make a string read the same forwards and backwards.
Given a string struefalsetrue
Example 1
Output: true
Example 2
Output: true
Explanation: delete the b or the c.
Example 3
Output: false
The Idea
A palindrome is a word that reads the same forwards and backwards, such as "level" or "racecar". In this problem we may also delete one character first. Example 2, "abca", is not a palindrome, but deleting its b leaves "aca", which is.
Which character should go? The simple answer is to try each one: delete it, then check what is left. For a string of n characters, that is n checks of up to n steps each. Is there a way to know where to look instead?
Check the string the way you would check any palindrome, from both ends. Put one marker, lohilohi
The pairs outside the b and the c already match, so they can stay as they are. That leaves the b and the c facing each other, and two different characters cannot form a pair. So one of these two must be the deleted character, and no other.
In "abca" either choice works: deleting the b leaves "c" between the two a's, and deleting the c leaves "b". It is not always both, though. Look at the picture below, which checks the string "cbbcc".
In the row labelled first pair, lohilohi
So one walk from both ends finds the only place where a deletion can help, and at most two more checks give the answer. Markers that start at opposite ends of a string and step toward each other are usually called two pointers. The same walk, with no deletion, solves
Solution Approach
Turning that idea into code starts with a look at the slow way, then settles three things: how to find the first mismatch, how to check the two candidates, and how to check part of the string without copying it.
Trying every deletion
Why not delete each character in turn and check the rest? Each try builds a new string and checks it, which takes up to n steps, and there are n tries. For a string of 100,000 characters that adds up to about 1010 steps. The first mismatch narrows the n tries down to two.
Finding the first mismatch
Where do the markers start, and when do they stop? lohilohi
Checking the two candidates
What exactly is checked at the mismatch? Deleting the character at lolo + 1hihilohi - 1true
Checking a range without copying
Each range could be cut out with substring
Java Solution
The method validPalindrome
- First, put
on index 0 andlo on the last index,hi .s.length() - 1 - A
loop runs as long aswhile . Whenlo < hi ands.charAt(lo) are the same, both markers move one step inward.s.charAt(hi) - At the first pair that differs, return the result of two calls to the helper
. The callisPalindrome skips the left character, andisPalindrome(s, lo + 1, hi) skips the right one. TheisPalindrome(s, lo, hi - 1) operator makes the second call only when the first returns|| .false - Inside
, a loop moves its own copies ofisPalindrome andlo inward over the range. It returnshi at the first pair that differs, andfalse if the markers meet.true - If the loop in
ends without a mismatch, returnvalidPalindrome : the string is already a palindrome.true
The main
public class ValidPalindromeII {
public static boolean validPalindrome(String s) {
int lo = 0;
int hi = s.length() - 1;
while (lo < hi) {
if (s.charAt(lo) != s.charAt(hi)) {
// one deletion allowed: drop the left or the right character
return isPalindrome(s, lo + 1, hi) || isPalindrome(s, lo, hi - 1);
}
lo++;
hi--;
}
return true;
}
private static boolean isPalindrome(String s, int lo, int hi) {
while (lo < hi) {
if (s.charAt(lo++) != s.charAt(hi--)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String[] inputs = {"aba", "abca", "abc", "cbbcc", "ccbbc", "ab", "abcxyba"};
for (String s : inputs) {
System.out.println(s + " -> " + validPalindrome(s));
}
}
}
Running it prints:
aba -> true
abca -> true
abc -> false
cbbcc -> true
ccbbc -> true
ab -> true
abcxyba -> false
"abc" gives false
Now look at "cbbcc -> true" and "ccbbc -> true". In "cbbcc" only deleting the right character of the mismatched pair works, as in the picture. In "ccbbc" it is the other way round: the mismatch is the c at index 1 and the b at index 3, and only deleting the left character, the c, works: it leaves "cbbc". A version that tries only the left side returns falsefalse
"ab -> true" mismatches straight away, and isPalindrome(s, 1, 1)false
The original implementation,
Complexity
The work is one walk from both ends that stops at the first mismatch, plus at most two checks of the part in between.
- Time: O(n) for a string of n characters. The walk compares each outer pair once, and the two
calls each compare the inner pairs at most once, so no character is looked at more than three times.isPalindrome - Space: O(1). The method keeps only
andlo , and the helper works on index ranges ofhi instead of building substrings.s