Introduction
The Valid Palindrome II problem involves checking whether a string can become a palindrome after deleting at most one character.
Given a string s, the task is to determine:
- whether the string can become palindrome
- after removing at most one character
This problem helps in understanding:
- Two Pointer Technique
- palindrome validation
- conditional skipping
- string comparison logic
Example
Input:s = "abca"
Output: True
Explanation: Removing 'c' gives:
"aba"
which is a palindrome.
Input:
s = "abc"
Output:
False
Explanation:
Removing one character still
cannot make the string palindrome.
Constraints
1 <= s.length <= 10^5s contains lowercase English lettersApproach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Remove each character one by one
- Check whether resulting string becomes palindrome
This approach works but repeated palindrome checking increases time complexity.
Steps
- Traverse every index.
- Remove current character.
- Check whether modified string is palindrome.
- If palindrome found:
- return true
- Otherwise:
- return false
Dry Run
Input:s = "abca"
Remove a:
"bca"
Not palindrome
Remove b:
"aca"
Palindrome found
Final Result:
True
Brute Force Code
Complexity Analysis
Time Complexity: O(n²)Explanation:
Palindrome checking is repeated
for every character.
Space Complexity: O(n)
Explanation:
Extra strings are created.
Approach 2 : Optimized Solution (Two Pointer Technique)
Explanation
The optimized solution uses the Two Pointer Technique.
The idea is:
- Compare characters from both ends
- If mismatch occurs:
- skip left character
OR - skip right character
- skip left character
- Check whether remaining substring becomes palindrome
This avoids repeated full traversal.
Steps
- Initialize:
- left = 0
- right = n - 1
- Compare characters.
- If mismatch occurs:
- check skipping left
- check skipping right
- Return result accordingly.
Dry Run
Input:s = "abca"
Initially:
left = 0 → a
right = 3 → a
Characters match
Move pointers
left = 1 → b
right = 2 → c Mismatch found
Check: Skip b → "ca"
Not palindrome
Skip c → "ba"
Not palindrome Check remaining substring:
"aba"
Palindrome found
Final Result:
True
Optimized Code
Complexity Analysis
Time Complexity: O(n)Explanation:
String is traversed at most twice.
Space Complexity: O(1)
Explanation:
No extra data structures are used.
Edge Cases