Valid Palindrome II

Decide whether deleting at most one character can make a string read the same forwards and backwards.

Given a string s, return true if it reads the same forwards and backwards after deleting at most one of its characters, and false otherwise. Deleting nothing is allowed too, so a string that already reads the same both ways gives true.

Example 1
Input: s = "aba"
Output: true
Example 2
Input: s = "abca"
Output: true
Explanation: delete the b or the c.
Example 3
Input: s = "abc"
Output: false
Solution

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, lo, on the first character and another, hi, on the last. While the two characters match, move both one step toward the middle. In "abca", the two a's match. Then lo is on the b and hi on the c, and these differ.

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".

The string cbbcc checked from both ends. In the first pair, lo and hi are on the c's at indices 0 and 4, which match. In the second pair, lo is on the b at index 1 and hi on the c at index 3, a mismatch. Deleting the b leaves indices 2 to 3, b and c, which is not a palindrome. Deleting the c leaves indices 1 to 2, b and b, which is.

In the row labelled first pair, lo and hi sit on the c's at indices 0 and 4, and they match. In the row labelled second pair, lo is on the b at index 1 and hi on the c at index 3: a mismatch. The box on the left deletes the b and checks indices 2 to 3, "bc", which fails. The box on the right deletes the c and checks indices 1 to 2, "bb", which reads the same both ways. So "cbbcc" works, by deleting the c at index 3 to get "cbbc".

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 Valid Palindrome.

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? lo starts at index 0 and hi at the last index. They keep moving inward while lo is left of hi. In a string of odd length, like "aba", they finally meet on the middle character, which has no partner and needs none. If they meet or cross without a mismatch, the string is already a palindrome.

Checking the two candidates

What exactly is checked at the mismatch? Deleting the character at lo leaves the range from lo + 1 to hi to compare, and deleting the one at hi leaves the range from lo to hi - 1. The one deletion is now spent, so each range must be a palindrome as it is, with no further mismatch allowed. If either range passes, the answer is true.

Checking a range without copying

Each range could be cut out with substring and checked as a new string. But that copies the characters first. A small helper method that takes the string and the two end indices walks the range directly, so no new string is made.

Java Solution

The method validPalindrome works in these steps:

  1. First, put lo on index 0 and hi on the last index, s.length() - 1.
  2. A while loop runs as long as lo < hi. When s.charAt(lo) and s.charAt(hi) are the same, both markers move one step inward.
  3. At the first pair that differs, return the result of two calls to the helper isPalindrome. The call isPalindrome(s, lo + 1, hi) skips the left character, and isPalindrome(s, lo, hi - 1) skips the right one. The || operator makes the second call only when the first returns false.
  4. Inside isPalindrome, a loop moves its own copies of lo and hi inward over the range. It returns false at the first pair that differs, and true if the markers meet.
  5. If the loop in validPalindrome ends without a mismatch, return true: the string is already a palindrome.

The main method runs the three examples, then "cbbcc" and "ccbbc", where only one side of the mismatch can be deleted, "ab", where either letter can go, and "abcxyba", which would need two deletions.

Java
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:

Output
aba -> true
abca -> true
abc -> false
cbbcc -> true
ccbbc -> true
ab -> true
abcxyba -> false

"abc" gives false because its first pair, a and c, already differs, and neither "bc" nor "ab" is left as a palindrome after one deletion.

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 false for "cbbcc", and one that tries only the right side returns false for "ccbbc", so both calls are needed.

"ab -> true" mismatches straight away, and isPalindrome(s, 1, 1) checks a single character, which always passes. In the last line, "abcxyba" matches the a's and the b's, then stops at c and y. Deleting the c leaves "xy" and deleting the y leaves "cx", so the answer is false.

The original implementation, ValidPalindromeII.java, is on GitHub.

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 isPalindrome calls each compare the inner pairs at most once, so no character is looked at more than three times.
  • Space: O(1). The method keeps only lo and hi, and the helper works on index ranges of s instead of building substrings.