Valid Palindrome II - Problem

Given a string s, return true if the string can be a palindrome after deleting at most one character from it.

A palindrome reads the same forward and backward. For example, "racecar" and "level" are palindromes.

Your task is to determine if removing zero or one character can make the string a palindrome.

Input & Output

Example 1 — Can Make Palindrome
$ Input: s = "aba"
Output: true
💡 Note: "aba" is already a palindrome, so we return true without deleting any character
Example 2 — Need One Deletion
$ Input: s = "abca"
Output: true
💡 Note: We can delete 'c' to get "aba" or delete 'b' to get "aca", both are palindromes
Example 3 — Cannot Make Palindrome
$ Input: s = "abc"
Output: false
💡 Note: No matter which character we delete, we cannot make it a palindrome with just one deletion

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters only

Visualization

Tap to expand
Valid Palindrome II Can we make a palindrome by removing at most one character? INPUT String s = "aba" a idx 0 b idx 1 a idx 2 Two Pointer Approach left right Input Details s = "aba" Length: 3 Deletions allowed: 1 ALGORITHM STEPS 1 Initialize Pointers left=0, right=len-1 2 Compare Characters s[left] == s[right]? 3 If Match: Move Both left++, right-- 4 If Mismatch: Try Skip Skip left OR right char Execution Trace Iter 1: s[0]='a' == s[2]='a' --> Match! Move pointers Iter 2: left=1, right=1 --> Pointers crossed! Done FINAL RESULT Original string is already a palindrome! a b a mirrors Output: true 0 deletions needed Verification "aba" reads same forward and backward Key Insight: Use two pointers from both ends. When mismatch found, try skipping either left OR right character. If either skip results in palindrome, return true. Time: O(n), Space: O(1) - optimal two-pass solution. TutorialsPoint - Valid Palindrome II | Optimal Solution
Asked in
Facebook 45 Microsoft 38 Amazon 32 Google 28
125.0K Views
High Frequency
~15 min Avg. Time
3.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen