Valid Palindrome II solution explained
Valid Palindrome II asks whether a string can be made into a palindrome by deleting at most one character. Walk two pointers inward from both ends; while the characters match, keep going. At the first mismatch you have exactly two options, skip the left character or skip the right one, so check whether either remaining middle section is a palindrome. That is O(n) time and O(1) extra space.
By Evin JohnPublished 7 min read
The task, restated
Given a string of lowercase letters, decide whether you can delete zero or one character so that the result reads the same forwards and backwards. You only return true or false; you do not need to say which character to delete, although that is a common follow-up. Strings can be long, so an approach that rebuilds the string for every possible deletion will be too slow.
| Input | Answer | Why |
|---|---|---|
| racecar | true | Already a palindrome, no deletion needed |
| abcca | true | Delete b to get acca |
| cbbcc | true | Delete the final c to get cbbc |
| abbab | true | Delete the last b to get abba; deleting the first a does not work |
| abcdef | false | No single deletion helps |
| ab | true | Delete either letter |
Ask whether the input may contain uppercase letters, spaces or punctuation. In the plain version it does not. If it does, the interviewer is mixing in the first Valid Palindrome problem, where you skip non-alphanumeric characters and compare case-insensitively, and you can fold that into the same pointer loop.
Why it is asked
This is a short two-pointer problem with one sharp edge. Many candidates write the loop correctly, then try to decide which character to skip by looking one step ahead, and that greedy choice is wrong on some inputs. The interviewer is checking whether you see that both branches have to be tried, and whether you can argue the total cost is still linear. Common follow-ups:
- Return the index to delete, or -1. Same loop: if the range i + 1 to j passes, the character to delete is at i; if i to j - 1 passes, it is at j. If the string is already a palindrome, return -1 or agree on another signal with the interviewer.
- Allow up to k deletions. Branching on every mismatch becomes exponential. The minimum number of deletions is the length minus the longest palindromic subsequence, which takes O(n²) dynamic programming.
- Count the palindromic substrings instead. A different problem with a center-expansion solution, covered on our Palindromic Substrings page.
Brute force: delete each index
If the string is already a palindrome, return true. Otherwise, for each index, build the string without that character and check whether it is a palindrome. There are n candidates and each check is O(n), so the whole thing is O(n²) time with O(n) extra space for the rebuilt string. It is easy to trust, which makes it the reference for testing.
def almost_palindrome_slow(s):
if s == s[::-1]:
return True
for k in range(len(s)):
t = s[:k] + s[k + 1:]
if t == t[::-1]:
return True
return FalseOptimal approach: two pointers, two branches
Start i at the left end and j at the right end. While s[i] equals s[j], move both inward. If they meet or cross, the string was already a palindrome. At the first mismatch, the outer part is fine and one of the two mismatched characters must go. So test two ranges with a plain palindrome check: i + 1 to j (left character removed) and i to j - 1 (right character removed). If either is a palindrome, the answer is true. Each range check is linear, and you run at most two of them, so the total stays O(n).
def is_pal_range(s, i, j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
def almost_palindrome(s):
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
return is_pal_range(s, i + 1, j) or is_pal_range(s, i, j - 1)
i += 1
j -= 1
return Truefunction isPalRange(s, i, j) {
while (i < j) {
if (s[i] !== s[j]) return false;
i++;
j--;
}
return true;
}
function almostPalindrome(s) {
let i = 0;
let j = s.length - 1;
while (i < j) {
if (s[i] !== s[j]) {
return isPalRange(s, i + 1, j) || isPalRange(s, i, j - 1);
}
i++;
j--;
}
return true;
}Checking ranges by index avoids building substrings, which keeps extra space at O(1). Python slicing such as s[i + 1:j + 1] would be shorter to write but copies the middle each time; mention the tradeoff if you use it.
Why only the first mismatch matters
Before the first mismatch, every outer pair already matches. At the mismatch, s[i] and s[j] cannot both survive as partners. A deletion strictly between them leaves this broken pair in place, so it cannot help, and a careful argument shows that deleting one of the already-matched outer characters never succeeds where deleting s[i] or s[j] fails. After choosing which side to skip, no more deletions are allowed, so the rest is a strict palindrome check. That is why one level of branching is enough. The tests behind this page compare the method with the brute force on every string of up to nine letters over a three-letter alphabet, and they agree.
The greedy trap: abbab
| Step | i, j | Characters | Result |
|---|---|---|---|
| 1 | 0, 4 | a vs b | mismatch |
| Skip left | check 1 to 4 | bbab | not a palindrome |
| Skip right | check 0 to 3 | abba | palindrome, answer true |
A tempting shortcut says: if s[i + 1] equals s[j], skip the left character, otherwise skip the right. Here s[1] is b and s[4] is b, so the shortcut skips the left a and checks bbab, which fails, and returns false. Both look-ahead conditions are true on this input (s[0] also equals s[3]), and only one of them leads anywhere. Checking both branches costs at most one extra linear pass and removes the guesswork.
Time and space
| Approach | Time | Extra space |
|---|---|---|
| Delete each index and test | O(n²) | O(n) |
| Two pointers with both branches | O(n) | O(1) |
| Up to k deletions with LPS dynamic programming (follow-up) | O(n²) | O(n) with a rolling row |
Edge cases
- Empty string and single character: true, with the loop never running.
- Two different characters: true, since deleting either leaves one character.
- Already a palindrome: true without any deletion.
- Mismatch at the very center of an even-length string, such as abxyba: deleting x or y works.
- A long string needing two deletions: false, after at most about two linear passes.
Mistakes to avoid
- Picking one side to skip by peeking at the next character instead of testing both.
- Allowing a second skip inside the range checks, which answers a different question.
- Building a new string for each check and calling it O(1) space.
- Off-by-one in the range bounds: skip left means i + 1 to j, skip right means i to j - 1, both inclusive.
- Forgetting that zero deletions is allowed, and returning false for a string that is already a palindrome.
How to explain it out loud
Fictional example
- Candidate
- Two pointers from the ends. While they match I move inward. If they cross, it was already a palindrome.
- Candidate
- At the first mismatch one of those two characters has to go, but I can't tell which by looking ahead, so I check both middles: without the left one and without the right one.
- Candidate
- Each check is linear and I do at most two, so it's O of n time and constant space. If you want the index to delete, I return whichever side passed.
Related problems
Minimum Remove to Make Valid Parentheses is also about the fewest deletions that repair a string, solved with a stack instead of two pointers. Buildings With an Ocean View is another one-pass array scan that rewards picking the right direction to walk. Longest Palindromic Substring is the natural next palindrome problem.
Natively as a practice tool
On Mac or Windows, Natively can read a short string problem from a screenshot during practice and propose code, which is a quick way to see whether another approach falls into the look-ahead trap you avoided. It also transcribes what you say, so you can review whether you explained why both branches are needed. See the AI interview assistant page for setup.
Questions people ask
How do you solve Valid Palindrome II?
Move two pointers inward from both ends while the characters match. At the first mismatch, check whether the middle is a palindrome with the left character skipped or with the right character skipped.
Why do you need to check both sides at the mismatch?
Looking one character ahead cannot tell you which side to skip. On abbab, both look-ahead tests pass, but only skipping the right character leads to a palindrome.
What is the time complexity of Valid Palindrome II?
O(n) time and O(1) extra space: one pass to the first mismatch, then at most two linear range checks.
What if up to k deletions are allowed?
Branching at every mismatch becomes exponential. Compute the longest palindromic subsequence with dynamic programming; the minimum deletions needed is the length minus that value.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
