Valid Palindrome II

Updated on 07 July, 2025
Valid Palindrome II header image

Problem Statement

The problem is to determine if a provided string s can be rearranged into a palindrome by the deletion of at most one character. A palindrome is a word, phrase, number, or other sequence of characters which reads the same forward and backward, ignoring spaces, punctuation, and capitalization. The task involves both identifying non-palindromic patterns and applying minimal alterations (specifically, single-character deletions) to potentially transform the sequence into a valid palindrome.

Examples

Example 1

Input:

s = "aba"

Output:

true

Example 2

Input:

s = "abca"

Output:

true

Explanation:

You could delete the character 'c'.

Example 3

Input:

s = "abc"

Output:

false

Constraints

  • 1 <= s.length <= 105
  • s consists of lowercase English letters.

Approach and Intuition

To solve this problem, we need to understand under what circumstances it is possible to convert a string into a palindrome by removing at most one character:

  1. Iteration Through Characters:

    • A direct way to assess the problem is to use two pointers technique—one pointer starting from the beginning of the string (left) and the other from the end (right).
  2. Identifying Non-matching Characters:

    • Move both pointers toward the center until a mismatch is found. The palindrome distribution is symmetrical; if characters at position left and right do not match, it indicates a potential disruption in this symmetry.
  3. Handling the Mismatch:

    • When a mismatch (non-matching characters) is spotted, there are two potential adjustments to test:
      • Remove the character pointed to by left and check if the rest of the string (from left+1 to right) is a palindrome.
      • Remove the character at right and verify if the string from left to right-1 is a palindrome.
  4. Verification Steps:

    • Implement a helper function that takes a substring and determines if it is a palindrome by iterating inwards from its ends. If either adjusted substring forms a palindrome, then it is possible to create a palindrome by removing one character from the original string.

This strategy employs a linear scan to detect the first anomaly and then a decision to possibly eliminate the trouble-causing character —effectively splitting the problem into simpler verification tasks. This alignment of checks and balances ensures efficiency while thoroughly assessing the structural potential of the string.

Solutions

  • Java
java
class Solution {
    private boolean isPalindromic(String str, int left, int right) {
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
                
            left++;
            right--;
        }
            
        return true;
    }
        
    public boolean validPalindrome(String str) {
        int left = 0;
        int right = str.length() - 1;
            
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return (isPalindromic(str, left, right - 1) || isPalindromic(str, left + 1, right));
            }
                
            left++;
            right--;
        }
            
        return true;
    }
}

The provided Java solution addresses the problem of checking whether a given string can be considered a palindrome if at most one character can be removed. The solution employs a two-pointer technique in combination with helper function isPalindromic to achieve this.

  • Start by defining the method isPalindromic that takes in the string str and two indices, left and right. This method iterates through the string from both ends towards the center, checking if characters at these positions match. If any mismatch is found, false is returned. If no mismatches are detected, true is returned.

  • The validPalindrome method sets two pointers, left starting at the beginning and right at the end of the string. These pointers move towards each other. Whenever a mismatch between characters at these pointers is found, the method checks two scenarios using isPalindromic:

    • By removing the character at the right pointer (i.e., checking the substring from left to right-1).
    • By removing the character at the left pointer (i.e., checking the substring from left+1 to right). If either scenario returns true, then removing one character can make the string a palindrome, so true is returned. If mismatches persist, false is returned.
  • If the entire string is traversed without finding a non-removable mismatch, it is considered a palindrome, and true is returned.

This approach ensures that the string is checked for palindromic properties with the flexibility of omitting one character if necessary, effectively catering to the problem’s requirements using efficient string manipulation and conditional checks.

  • Python
python
class Solution:
    def isPalindromeAdjustable(self, string: str) -> bool:
        def is_sub_palindrome(sub_s, left, right):
            while left < right:
                if sub_s[left] != sub_s[right]:
                    return False
                left += 1
                right -= 1
            return True
            
        left = 0
        right = len(string) - 1
        while left < right:
            if string[left] != string[right]:
                return is_sub_palindrome(string, left, right - 1) or is_sub_palindrome(string, left + 1, right)
            left += 1
            right -= 1
                
        return True

This Python solution defines a method to determine if a given string can be modified to become a palindrome by removing at most one character. The primary method isPalindromeAdjustable utilizes an inner function is_sub_palindrome to check if sections of the string are palindromes.

  • The is_sub_palindrome function uses a two-pointer approach to check for palindromicity between two indices in the string.
  • In the main function isPalindromeAdjustable:
    1. Two pointers, left and right are initialized at the start and end of the string respectively.
    2. A while loop is run as long as left is less than right.
    3. If characters at these pointers do not match:
      1. Two possibilities are checked:
        • Skipping the character at the right pointer and checking if the remaining substring is a palindrome.
        • Skipping the character at the left pointer and checking again.
      2. If either case returns true, the main function returns true.
    4. If all characters match in pairs, the function confirms the string is already a palindrome or can be converted into one by a single modification.

This approach efficiently checks for possible palindromes with minimal changes, ensuring a solution suitable for strings where at most one adjustment is allowed to achieve palindromicity.

Comments

No comments yet.