easy Valid Palindrome II
Problem Statement
Given string s, determine whether it's possible to make a given string palindrome by removing at most one character.
A palindrome is a word or phrase that reads the same backward as forward.
Examples
-
Example 1:
- Input:
"racecar" - Expected Output:
true - Justification: The string is already a palindrome, so no removals are needed.
- Input:
-
Example 2:
- Input:
"abccdba" - Expected Output:
true - Justification: Removing the character 'd' forms the palindrome "abccba".
- Input:
-
Example 3:
- Input:
"abcdef" - Expected Output:
false - Justification: No single character removal will make this string a palindrome.
- Input:
Constraints:
- 1 <= s.length <= 105
strconsists of lowercase English letters.
Try it yourself
Try solving this question here:
✅ Solution Valid Palindrome II
Problem Statement
Given string s, determine whether it's possible to make a given string palindrome by removing at most one character.
A palindrome is a word or phrase that reads the same backward as forward.
Examples
-
Example 1:
- Input:
"racecar" - Expected Output:
true - Justification: The string is already a palindrome, so no removals are needed.
- Input:
-
Example 2:
- Input:
"abeccdeba" - Expected Output:
true - Justification: Removing the character 'd' forms the palindrome "abccba".
- Input:
-
Example 3:
- Input:
"abcdef" - Expected Output:
false - Justification: No single character removal will make this string a palindrome.
- Input:
Constraints:
- 1 <= s.length <= 105
strconsists of lowercase English letters.
Solution
To solve this problem, we use a two-pointer approach that initiates at both ends of the string. These pointers move towards the center, comparing characters at each step. Upon encountering a mismatch, the algorithm decides whether to skip the character at the left or the right pointer. A helper function is used to check if the resulting substring (after skipping a character) forms a palindrome. This process is performed twice, once for each pointer. If either scenario results in a palindrome, the original string can be considered a valid palindrome after removing at most one character. This efficient method determines the feasibility of forming a palindrome with minimal alterations to the string.
-
Initialization: Begin by initializing the
leftpointer with 0 and therightpointer with n - 1, where n is a string length. -
Two-Pointer Traversal: Use two pointers, and move these pointers towards the center, comparing the characters at each step.
-
Handling Mismatch: Upon encountering a mismatch, the algorithm checks two scenarios: removing the character at the left pointer or at the right pointer. For each scenario, it checks if the remaining substring forms a palindrome.
-
Greedy Decision Making: If either resulting substring is a palindrome, return true. This decision is based on the greedy principle that choosing the first viable option (resulting in a palindrome) is sufficient.
-
Concluding Result: If neither scenario results in a palindrome, the algorithm concludes that it's impossible to form a palindrome by removing just one character and returns false.
This greedy approach is efficient as it minimizes the number of checks needed to determine if the string can be a valid palindrome with a single character removal.
Algorithm Walkthrough
Input:- "abeccdeba"
-
Initial Setup:
- Two pointers are initialized:
leftat the start (pointing to'a') andrightat the end (pointing to'a').
- Two pointers are initialized:
-
First Iteration:
- Compare characters at
leftandrightpointers. - Characters are the same (
'a'), so moveleftto the right andrightto the left.
- Compare characters at
-
Second Iteration:
- Now
leftpoints to'b'andrightpoints to'b'. - Characters match, so move
leftandrightinward again.
- Now
-
Third Iteration:
leftis now at'e', andrightis at'e'.- Characters match, so move
leftandrightinward again.
-
Fourth Iteration:
leftis now at'c', andrightis at'd'.- Characters do not match. This is where a decision is made.
-
Checking Substrings:
- Remove the character at the
leftpointer ('c') and check if the substring"cd"is a palindrome. It is not. - Remove the character at the
rightpointer ('d') and check if the substring"cc"is a palindrome. It is a palindrome.
- Remove the character at the
-
Conclusion:
- Since removing the character
'd'(at therightpointer) resulted in a palindrome, the answer istrue.
- Since removing the character
Code
Here is the code for this algorithm:
public class Solution {
// Method to check if it's possible to form a palindrome
public boolean isPalindromePossible(String s) {
int left = 0,
right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
// Check by removing either left or right character
return (
isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1)
);
}
left++;
right--;
}
return true; // String is already a palindrome
}
// Helper method to check if a substring is a palindrome
private static boolean isPalindrome(String s, int left, int right) {
while (left < right) {
if (s.charAt(left++) != s.charAt(right--)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.isPalindromePossible("racecar")); // true
System.out.println(sol.isPalindromePossible("abccdba")); // true
System.out.println(sol.isPalindromePossible("abcdef")); // false
}
}
Complexity Analysis
- Time Complexity: O(n) for traversing the string.
- Space Complexity: O(1) as no extra space is used.
🤖 Don't fully get this? Learn it with Claude
Stuck on Valid Palindrome II? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Valid Palindrome II** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Valid Palindrome II** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Valid Palindrome II**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Valid Palindrome II**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.