Valid Palindrome II - Problem
Given a string s, determine if it can become a palindrome by deleting at most one character from it.
A palindrome is a string that reads the same forwards and backwards, like "racecar" or "madam". Your task is to check if the given string is already a palindrome, or if removing exactly one character can make it a palindrome.
Examples:
"aba"→true(already a palindrome)"abca"→true(remove 'c' to get "aba")"abc"→false(cannot be made palindrome by removing one character)
Input & Output
example_1.py — Basic Case
$
Input:
s = "aba"
›
Output:
true
💡 Note:
"aba" is already a palindrome, so no deletion is needed
example_2.py — Single Deletion
$
Input:
s = "abca"
›
Output:
true
💡 Note:
We can remove the 'c' at index 2 to get "aba", which is a palindrome
example_3.py — Impossible Case
$
Input:
s = "abc"
›
Output:
false
💡 Note:
No single character removal can make "abc" a palindrome. Removing any character gives "bc", "ac", or "ab", none of which are palindromes
Visualization
Tap to expand
Understanding the Visualization
1
Start Inspection
Place inspectors at both ends of the mirror text
2
Walk Inward
Move inspectors toward center while characters match
3
Find Defect
When mismatch found, this is our potential deletion point
4
Try Fixes
Test removing either left or right character
5
Verify Fix
Check if remaining text forms perfect palindrome
Key Takeaway
🎯 Key Insight: When two pointers find a mismatch, we only need to try removing one of the two mismatched characters - this eliminates the need to check all possible deletions!
Time & Space Complexity
Time Complexity
O(n)
In worst case, we scan the string once and do one additional palindrome check
✓ Linear Growth
Space Complexity
O(1)
Only using a few pointer variables, no extra data structures
✓ Linear Space
Constraints
- 1 ≤ s.length ≤ 105
- s consists of lowercase English letters only
- At most one character can be deleted
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code