Valid Palindrome II (LeetCode 680): Solution and Explanation
Given a string of lowercase letters, decide whether it can be turned into a palindrome by deleting at most one character. A string that is already a palindrome counts as valid without any deletion.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force tries deleting each character in turn and checks whether what is left is a palindrome. That is n deletions, each followed by an O(n) check, for O(n²) total. With strings up to 100,000 characters, that is too slow.
The usual palindrome check walks two pointers inward from both ends, comparing characters. As long as they match, nothing needs to change, and the outer characters can be ignored from then on. The interesting moment is the first mismatch. At that point one of the two mismatched characters must be the one you delete, because every pair outside them already matched and deleting anything else would leave this pair mismatched.
So at the first mismatch there are only two options: skip the left character or skip the right one. Check whether the remaining inner substring is a palindrome for either option. You do not need to allow a second deletion inside those checks, because the budget is only one. That turns the problem into one scan plus at most two more linear scans, so the whole thing runs in O(n). The insight worth remembering is that a single mismatch pins down exactly where the deletion must happen, which removes the need to guess.
Approach: Two pointers with one skip
- Define a helper
isPalin(l, r)that checks whethers[l..r]is a palindrome by walking two pointers inward. - Set
left = 0andright = len(s) - 1. - While
left < right, compares[left]ands[right]. - On a mismatch, return
isPalin(left + 1, right) or isPalin(left, right - 1), which tries deleting the left character and then the right one. - On a match, move
leftforward andrightbackward. - If the pointers meet without any mismatch, return True.
Step-by-step example
s = "cbbcc"
left = 0andright = 4both hold 'c', so the pointers move to 1 and 3.s[1]is 'b' ands[3]is 'c', which is the first mismatch.- Deleting the left character means checking
s[2..3], which is 'bc'. That is not a palindrome. - Deleting the right character means checking
s[1..2], which is 'bb'. That is a palindrome, so the function returns True. Removing the 'c' at index 3 leaves 'cbbc'.
Code: Python, Java, C++
1class Solution:
2 def validPalindrome(self, s: str) -> bool:
3 def isPalin(l, r):
4 while l < r:
5 if s[l] != s[r]:
6 return False
7 l += 1
8 r -= 1
9 return True
10
11 left, right = 0, len(s) - 1
12 while left < right:
13 if s[left] != s[right]:
14 return isPalin(left + 1, right) or isPalin(left, right - 1)
15 left += 1
16 right -= 1
17 return True1class Solution {
2 public boolean validPalindrome(String s) {
3 int left = 0, right = s.length() - 1;
4 while (left < right) {
5 if (s.charAt(left) != s.charAt(right)) {
6 return isPalin(s, left + 1, right) || isPalin(s, left, right - 1);
7 }
8 left++;
9 right--;
10 }
11 return true;
12 }
13
14 private boolean isPalin(String s, int l, int r) {
15 while (l < r) {
16 if (s.charAt(l) != s.charAt(r)) return false;
17 l++;
18 r--;
19 }
20 return true;
21 }
22}1class Solution {
2public:
3 bool validPalindrome(string s) {
4 int left = 0, right = s.size() - 1;
5 while (left < right) {
6 if (s[left] != s[right]) {
7 return isPalin(s, left + 1, right) || isPalin(s, left, right - 1);
8 }
9 left++;
10 right--;
11 }
12 return true;
13 }
14
15 bool isPalin(string& s, int l, int r) {
16 while (l < r) {
17 if (s[l] != s[r]) return false;
18 l++;
19 r--;
20 }
21 return true;
22 }
23};Time and space complexity
O(n)
The main loop scans at most n / 2 pairs, and after the first mismatch the two helper calls each scan at most the remaining inner range once.
O(1)
Only index variables are used. No substrings are created because the helper works on index ranges.
Other approaches
Try every deletion (time O(n²), space O(n))
For each index, build the string without that character and test whether it is a palindrome. It is simple and correct but takes O(n²) time and creates many temporary strings.
Recursive helper with a deletion budget (time O(n), space O(n))
Write one recursive function that takes the range and the number of deletions left. It generalizes neatly to allowing k deletions, though for k greater than one you would add memoization to avoid exponential branching.
Common mistakes
- Only trying to skip one side at the mismatch. Inputs such as 'cbbcc' need the right skip and others need the left, so both must be tried.
- Continuing the main loop after a skip instead of handing off to the helper, which effectively allows more than one deletion.
- Building substrings with slicing in the helper calls. It still works but adds O(n) allocation; passing indices avoids it.
- Mixing this up with the original Valid Palindrome. This version has only lowercase letters, so there is no need to filter punctuation or normalize case.
Frequently asked questions
Why are two checks enough at the first mismatch?
All pairs outside the mismatch already match, so any valid deletion must remove one of the two mismatched characters. Trying both possibilities covers every option, and each only needs a plain palindrome check.
What is the time complexity of Valid Palindrome II?
It is O(n). The outer scan and the two inner checks each walk the string at most once, and the space is O(1).
How would you allow up to k deletions?
Use a recursive function on (left, right, deletions left) that branches at mismatches, and memoize it. Alternatively, compute the longest palindromic subsequence and check whether the string length minus it is at most k.
Does a string that is already a palindrome count?
Yes. At most one deletion means zero deletions is allowed, so a palindrome like 'aba' returns True without using the skip. The main loop finds no mismatch, the pointers meet in the middle, and the function falls through to its final return.