Magicsheet logo

Valid Palindrome II

Easy
73.6%
Updated 6/1/2025

Valid Palindrome II

What is this problem about?

The "Valid Palindrome II" interview question is a slight but significant twist on the classic palindrome check. In this version, you are given a string and asked if it can become a palindrome after deleting at most one character. If the string is already a palindrome, the answer is true. If it isn't, you must determine if removing a single character from any position can make it one.

Why is this asked in interviews?

This "Valid Palindrome II" coding problem is highly popular at companies like Meta and Amazon because it tests a candidate's ability to think beyond simple linear scans. It introduces a decision point: when two characters don't match, which one should you skip? It evaluates your understanding of the "Greedy interview pattern" and your ability to reuse existing logic (a standard palindrome check) within a more complex function.

Algorithmic pattern used

The primary algorithmic pattern is the "Two Pointers" technique combined with a "Greedy" approach. You use two pointers (left and right) moving towards the center. When you encounter a mismatch s[left] != s[right], you have two choices: skip the character at left and check if the remaining substring is a palindrome, OR skip the character at right and check the remaining substring. If either resulting substring is a palindrome, the whole string is valid.

Example explanation

Consider the string: "abca".

  1. Left pointer at index 0 ('a'), Right at index 3 ('a'). Match!
  2. Left moves to 1 ('b'), Right moves to 2 ('c'). Mismatch!
  3. Option A: Skip 'b' (left). Check substring "c". It's a palindrome.
  4. Option B: Skip 'c' (right). Check substring "b". It's a palindrome.
  5. Since we found a way by removing one character, the result is true.

Common mistakes candidates make

A common mistake is trying to use nested loops to remove every possible character one by one and checking for a palindrome, which results in O(n²) time complexity. Another error is failing to realize that you only need to check two specific substrings when the first mismatch occurs, rather than continuing to allow more deletions.

Interview preparation tip

For the "Valid Palindrome II" coding problem, always define a helper function isPalindrome(string, left, right) that checks a range. This makes your main function much cleaner and prevents you from writing redundant loop logic when you need to check the two potential substrings after a mismatch.

Similar Questions