Algo-Sim › Two Pointers
Valid Palindrome II
Easy · Two Pointers · step through it in Java, Python and C++ on your own input
Can the string become a palindrome by deleting at most one character? Two pointers; at the first mismatch, try skipping either side once.
Problem
Given a string s, return true if it can be a palindrome after deleting at most one character from it.
Constraints
- 1 ≤ s.length ≤ 10⁵
- s consists of lowercase English letters
Edge cases to test
- Already a palindrome
- The deletion must be on the left in one case and the right in another:
"abca" - Two characters
Follow-up questions
- Why try both sides only once?
- Before the first mismatch both ends agree, so the deletion must be one of the two mismatched characters. Each check is O(n), so O(n) overall.
- What if up to k deletions are allowed?
- The answer is whether n − LPS(s) ≤ k, where LPS is the longest palindromic subsequence: O(n²) DP (LC 1216).
Solution
Java
public boolean validPalindrome(String s) {
int l = 0, r = s.length() - 1;
while (l < r) {
if (s.charAt(l) != s.charAt(r))
// One deletion allowed: drop s[l] or drop s[r], and the rest must match.
return isPal(s, l + 1, r) || isPal(s, l, r - 1);
l++;
r--;
}
return true;
}
boolean isPal(String s, int l, int r) {
while (l < r) {
if (s.charAt(l) != s.charAt(r)) return false;
l++;
r--;
}
return true;
}Python
def valid_palindrome(s):
def is_pal(l, r):
while l < r:
if s[l] != s[r]:
return False
l, r = l + 1, r - 1
return True
l, r = 0, len(s) - 1
while l < r:
if s[l] != s[r]:
# One deletion allowed: drop s[l] or drop s[r], and the rest must match.
return is_pal(l + 1, r) or is_pal(l, r - 1)
l, r = l + 1, r - 1
return TrueC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
bool isPal(const string &s, int l, int r) {
while (l < r) {
if (s[l] != s[r]) return false;
l++;
r--;
}
return true;
}
public:
bool validPalindrome(string &s) {
int l = 0, r = int(s.size()) - 1;
while (l < r) {
if (s[l] != s[r])
// One deletion allowed: drop s[l] or drop s[r], and the rest must match.
return isPal(s, l + 1, r) || isPal(s, l, r - 1);
l++;
r--;
}
return true;
}
};
More Two Pointers problems
- Valid Palindrome (Easy)
- Two Sum II - Input Array Is Sorted (Medium)
- Remove Duplicates from Sorted Array (Easy)
- Move Zeroes (Easy)
- Container With Most Water (Medium)
- Trapping Rain Water (Hard)
- Sort Colors (Medium)
- Merge Sorted Array (Easy)
- Rotate Array (Medium)
- Next Permutation (Medium)
- 3Sum (Medium)