Valid Palindrome With One Optional Deletion
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Determine whether a lowercase text string s can read identically left-to-right and right-to-left after removing zero or one character from any index.
def can_be_palindrome_after_one_deletion(s: str) -> bool:
When a character is removed, all remaining characters stay in their original relative order. Because removing zero characters is valid, any input that is already symmetric—including every single-character string—must evaluate to True. Return False whenever two or more removals would be required.
Examples
Example 1
Input: s = "levmel"
Output: True
Dropping 'v' at index 2 produces "lemel", while dropping 'm' at index 3 produces "level". Either choice yields a valid palindrome.
Example 2
Input: s = "rotatxor"
Output: True
The outer pairs 'r' and 'o' already match; removing 'x' at index 5 leaves "rotator", which is symmetric.
Example 3
Input: s = "code"
Output: False
"code" is not symmetric as-is, and each single-character removal ("ode", "cde", "coe", "cod") still fails to match in reverse.
Constraints
1 <= len(s) <= 10^5- Every character in
sis a lowercase ASCII letter ('a'through'z').
Step-by-step walkthrough
Understand the goal
A palindrome is a string that reads identically from left to right and from right to left, such as
"racecar"or"abba". We are given a lowercase stringsof up to100,000characters and want to returnTrueifsis already a palindrome (zero deletions) or can become one by deleting one character from any position while keeping the remaining characters in order.s = "levmel" -> True (drop 'v' to get "lemel", or drop 'm' to get "level") s = "rotatxor" -> True (drop 'x' at index 5 to get "rotator") s = "code" -> False (one removal leaves "ode", "cde", "coe", or "cod" — none symmetric) s = "radar" -> True (already symmetric — zero removals used)Why the brute-force check is too slow
The most direct idea is to check whether
sis already a palindrome, and if not, try deleting index0, then index1, all the way up to indexn - 1. For each candidate indexi, buildings[:i] + s[i + 1:]and checking whether it equals its reverse copies and compares roughlyncharacters.Doing
O(n)work acrossncandidate positions takesO(n^2)total operations. Whenn = 100,000,n^2 = 10,000,000,000(ten billion character operations), which takes several seconds when no early deletion succeeds. We need a single linear scan that avoids copying strings.Key idea 1: peel off matching outer ends for free
Place two index pointers at the outer ends of the string:
left = 0andright = len(s) - 1. Whenevers[left] == s[right], those two characters already mirror each other, so we can move both pointers inward (left += 1,right -= 1) without spending our one allowed deletion.s = "r o t a t x o r" ^ ^ left=0 right=7 -> both are 'r', so peel them off and focus on "otatxo"A natural worry is: "What if
s[left] == s[right], could the only valid fix require deleting one of those outer characters?" Supposes = "ccac", wheres[0] == 'c'ands[3] == 'c'match. Deleting index0produces"cac". Because"cac"is a palindrome, its first character (originally at index1) must equal its last character'c'. That meanssstarts with"cc", so deleting index1(inside the middle!) produces the exact same string"cac". By the same logic on the right end, peeling off equal outer characters never loses a valid solution.Key idea 2: at the first mismatch, try both skips
Suppose our inward scan hits the first mismatch where
s[left] != s[right]. Look at the remaining unchecked substrings[left..right]:- If we delete neither
s[left]nors[right], any deletion deeper inside leavess[left]at the front ands[right]at the back — still a mismatch! - Therefore, our one and only deletion must remove either
s[left]ors[right]. - Once we spend that deletion, zero deletions remain, so the surviving substring must already be an exact palindrome:
- Skip left (
s[left]): checks[left + 1 .. right]. - Skip right (
s[right]): checks[left .. right - 1].
- Skip left (
Why must we test both choices instead of peeking one character ahead? Look at
"aabbaba"after peeling the outer'a's at indices0and6:index: 0 1 2 3 4 5 6 chars: a [a b b a b] a ^ ^ left=1 right=5 ('a' != 'b') Peek left+1: s[2] = 'b' matches s[5] = 'b', tempting us to skip left -> "bbab" (NOT a palindrome!) Peek right-1: s[4] = 'a' matches s[1] = 'a', skipping right -> "abba" (IS a palindrome!)Peeking one step ahead can fool us; checking both remaining slices takes linear time and never guesses wrong.
- If we delete neither
Write a slice-free helper for exact palindrome checks
To check whether
s[left..right]is an exact palindrome without allocating a new substring, passsalong with inclusive start and end indicesleftandright. Walk them toward the center until they meet (odd length) or cross (even length).def is_palindrome_range(s: str, left: int, right: int) -> bool: """Return True if s[left..right] (both endpoints inclusive) is a palindrome.""" # Walk both inclusive index pointers inward with zero deletions left. # Stop at left >= right: either they met on one middle char or crossed cleanly. while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return TrueWrite the main two-pointer scan
Now combine the outer scan with the two candidate range checks. If the
while left < rightloop finishes without ever hitting a mismatch, the string was already a palindrome (including single-character strings whereleft == right == 0right away), so we returnTrue.def can_be_palindrome_after_one_deletion(s: str) -> bool: # left, right: inclusive index bounds of the unchecked middle section s[left..right] left = 0 right = len(s) - 1 # Phase 1: greedily peel off matching outer pairs without spending our deletion. while left < right: if s[left] != s[right]: # Phase 2: first mismatch found. Keeping both s[left] and s[right] leaves # mismatched outer ends, so our single deletion MUST drop one of them. # Check both remaining inclusive ranges with zero further deletions allowed. skip_left = is_palindrome_range(s, left + 1, right) skip_right = is_palindrome_range(s, left, right - 1) return skip_left or skip_right left += 1 right -= 1 # Phase 3: no mismatch ever occurred, so s is already a palindrome (0 deletions). return TrueTrace Example 2 step by step
Let's trace
s = "rotatxor"(length8, indices0..7):index: 0 1 2 3 4 5 6 7 chars: r o t a t x o r 1. left = 0 ('r'), right = 7 ('r') -> match! Advance to left = 1, right = 6. 2. left = 1 ('o'), right = 6 ('o') -> match! Advance to left = 2, right = 5. 3. left = 2 ('t'), right = 5 ('x') -> MISMATCH! Split into two exact checks: Branch A (skip_left): is_palindrome_range(s, 3, 5) -> substring "atx" s[3] = 'a' vs s[5] = 'x' -> mismatch -> returns False Branch B (skip_right): is_palindrome_range(s, 2, 4) -> substring "tat" s[2] = 't' vs s[4] = 't' -> match! Advance to left = 3, right = 3 -> stop -> returns True 4. skip_left or skip_right -> False or True -> returns True!Removing index
5leaves"rotator", which is a palindrome.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def is_palindrome_range(s: str, left: int, right: int) -> bool: """Return True if s[left..right] (both endpoints inclusive) is a palindrome.""" # Walk both inclusive index pointers inward with zero deletions left. # Stop at left >= right: either they met on one middle char or crossed cleanly. while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True def can_be_palindrome_after_one_deletion(s: str) -> bool: # left, right: inclusive index bounds of the unchecked middle section s[left..right] left = 0 right = len(s) - 1 # Phase 1: greedily peel off matching outer pairs without spending our deletion. while left < right: if s[left] != s[right]: # Phase 2: first mismatch found. Keeping both s[left] and s[right] leaves # mismatched outer ends, so our single deletion MUST drop one of them. # Check both remaining inclusive ranges with zero further deletions allowed. skip_left = is_palindrome_range(s, left + 1, right) skip_right = is_palindrome_range(s, left, right - 1) return skip_left or skip_right left += 1 right -= 1 # Phase 3: no mismatch ever occurred, so s is already a palindrome (0 deletions). return True✅ Submit now — all tests should pass.
Intuition & how it works
A palindrome is a word that reads the same forwards and backwards, like "racecar". Imagine checking whether a beaded necklace has symmetric colors by placing your left thumb on the first bead, your right thumb on the last bead, and sliding both thumbs inward one bead at a time — while holding one "free snip" coupon that lets you cut out at most one mismatched bead. As long as the left and right beads match, you save your coupon and keep sliding inward; the moment your thumbs land on two different beads, your coupon must remove either the left bead or the right bead, and the remaining middle stretch has to match perfectly on its own.
The naive approach tries deleting each of the n positions one by one, slicing out a new (n - 1)-character string and comparing it with its reverse. Each slice and check touches O(n) characters, so testing all n positions takes O(n^2) character operations — roughly 10,000,000,000 operations when n = 100,000, which times out whenever no early deletion works. Instead, using the two-pointer technique (keeping two integer indices moving toward each other on the original string) skips all string copying and branches only once at the very first mismatch.
Walk through s = "rotatxor" (indices 0 to 7):
1. Start at the ends: s[0] == s[7] == 'r' and s[1] == s[6] == 'o' both match, so move inward to left = 2, right = 5.
2. Now s[2] = 't' and s[5] = 'x' disagree. Spend the single deletion in the only two possible ways:
- Delete s[2] and check s[3..5] = "atx" -> 'a' != 'x', so False.
- Delete s[5] and check s[2..4] = "tat" -> 't' == 't' and 'a' is the center, so True.
3. Because one branch succeeded, return True immediately.
Complexity
- Time:
O(n), wherenislen(s). Before the first mismatch,leftandrightlook at each outer pair once. At the first mismatch (if any),is_palindrome_rangeis called at most twice on the unvisited middle segment, so every character insis compared at most three times in total. - Space:
O(1)extra memory. Both the outer scan and the helper pass integer indices(left, right)into the original stringsinstead of slicing substrings or building reversed copies.
Edge cases
- Single character (
"z"):left = 0is not less thanright = 0, so the loop never runs and immediately returnsTrue. - Two distinct characters (
"ab"): Mismatches at(0, 1);is_palindrome_range(s, 1, 1)checks a 1-character slice (left == right) and returnsTrue. - Already a palindrome (
"racecar","abba","aaaa"): Zero deletions are allowed; the outer pointers cross cleanly and returnTrue. - Only one side works (
"babba"vs"aabbaba"): On"aabbaba", peeking one step ahead suggests both skips look plausible (s[2] == s[5]ands[1] == s[4]), yet only skipping the right character ("aabbaa") produces a palindrome. - Needs two or more deletions (
"abcdeba","abcd"): Bothskip_leftandskip_righthit a second mismatch and returnFalse. - Maximum length (
n = 10^5, such as"a" * 99999 + "b"): Runs in a few milliseconds because no substrings are copied.
Common mistakes
- Choosing one branch greedily by peeking at
s[left + 1] == s[right]: Fails on inputs like"aabbaba"wheres[left + 1] == s[right]is true by coincidence, causing you to discard the only working branch (skip_right). - Calling
can_be_palindrome_after_one_deletionrecursively on the slices instead ofis_palindrome_range: Without a remaining-deletions counter, recursion allows one deletion at every mismatch instead of one deletion total. - Slicing strings (
s[left + 1 : right + 1]) inside a loop over all indices: AllocatesO(n)characters per attempt and degrades toO(n^2)time on100,000-character strings. - Off-by-one bounds between inclusive indices and Python half-open slices: In
is_palindrome_range(s, left, right),rightis inclusive, so skippingleftchecks(left + 1, right)and skippingrightchecks(left, right - 1). - Returning
Falsewhen zero deletions are needed: The problem asks for at most one deletion, so an existing palindrome must returnTrue.
Follow-up questions
- How would you extend the algorithm if up to k character removals are permitted? When
kis small (for examplek <= 20), you can generalize the exact same idea with recursioncan_fix(left, right, remaining_k): advance inward whiles[left] == s[right], and on a mismatch trycan_fix(left + 1, right, remaining_k - 1)orcan_fix(left, right - 1, remaining_k - 1)with memoization (caching(left, right)failures so identical subproblems are never recomputed), which runs inO(n * 2^k)orO(n * k^2)time with banded dynamic programming (solving smaller subproblems in a table to avoid repeated work). For arbitrary largek, find the longest palindromic subsequence (the longest sequence of characters insthat already reads the same both ways without reordering) inO(n^2)time and check whetherlen(s) - longest_length <= k. - What changes if the caller wants the index of a character to remove rather than a boolean? Return
-1(orNone, depending on the agreed contract) if the outer scan finishes with no mismatch because zero deletions are needed. At the first mismatch(left, right), returnleftifis_palindrome_range(s, left + 1, right)isTrue, else returnrightifis_palindrome_range(s, left, right - 1)isTrue, else signal that no single deletion works (for example-2). Clarify tie-breaking with the interviewer since"levmel"can drop either index2or index3. - How can you adapt the scan to ignore letter case, whitespace, and punctuation? Keep the exact same two-pointer algorithm, but before each comparison advance
leftrightward past non-alphanumeric characters, advancerightleftward past non-alphanumeric characters, and compares[left].lower() == s[right].lower(). Apply the same non-alphanumeric skipping insideis_palindrome_range, keeping timeO(n)and extra spaceO(1).
Follow-up questions
- How would you extend the algorithm if up to k character removals are permitted?
- What changes if the caller wants the index of a character to remove rather than a boolean?
- How can you adapt the scan to ignore letter case, whitespace, and punctuation?
Similar questions
- Stateful Tic-Tac-Toe Engine and Mobile View
- User Action Sequence Prefix Tree
- Banned Phrase Chat Filter
- User Activity Prefix Counts
- Efficient Dot Product for Sparse Vectors
- Valid Keypad Sequences Under Knight Moves
More Whatnot interview questions
- User Action Sequence Prefix Tree Hard
- Valid Keypad Sequences Under Knight Moves Medium
- Stateful Tic-Tac-Toe Engine and Mobile View Medium Pro
- Live-Shopping Trending Stream Discovery Medium Pro
- Efficient Dot Product for Sparse Vectors Medium Pro
- Evaluate and Debug a Live-Shopping Marketplace App Medium Pro
- Month-over-Month Customer Retention Medium Pro
- Calendar-Aware 7-Day Moving Average in SQL Medium Pro
- Banned Phrase Chat Filter Medium Pro
- User Activity Prefix Counts Easy Pro