Given a string s
, return true
if the s
can be palindrome after deleting at most one character from it.
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.The problem asks whether a given string can become a palindrome by removing at most one character. The optimal solution leverages a two-pointer approach with a helper function for palindrome checking.
Approach:
Two Pointers: The main part of the solution uses two pointers, i
and j
, initialized to the start and end of the string, respectively. These pointers move inwards, comparing characters at each position.
Mismatch Handling: If a mismatch (s[i] != s[j]
) is found, it means we need to potentially remove one character to make it a palindrome. We have two possibilities: remove s[i]
or remove s[j]
.
Helper Function (check
): A helper function, check(i, j)
, efficiently determines if a substring (from index i
to j
) is a palindrome. This avoids redundant palindrome checks.
Recursive Calls: If a mismatch occurs, we recursively call check
twice:
check(i + 1, j)
: Checks if the substring after removing s[i]
is a palindrome.check(i, j - 1)
: Checks if the substring after removing s[j]
is a palindrome.Return Value: The function returns true
if either of the recursive calls returns true
(meaning a palindrome can be formed by removing at most one character), or if the loop completes without finding a mismatch (the string is already a palindrome).
Time Complexity: O(n) - The algorithm iterates through the string at most twice in the worst case (one for the main loop, and one for the helper function called once or twice).
Space Complexity: O(1) - The algorithm uses a constant amount of extra space.
Code Examples (Python):
class Solution:
def validPalindrome(self, s: str) -> bool:
def check(i, j):
while i < j:
if s[i] != s[j]:
return False
i, j = i + 1, j - 1
return True
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
return check(i + 1, j) or check(i, j - 1) # Try removing either char
i, j = i + 1, j - 1
return True # Already a palindrome
The other language examples follow a similar structure, adapting the syntax to their respective languages. The core logic remains consistent across all implementations.