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 s is a lowercase ASCII letter ('a' through 'z').

Step-by-step walkthrough

  1. 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 string s of up to 100,000 characters and want to return True if s is 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)
    
  2. Why the brute-force check is too slow

    The most direct idea is to check whether s is already a palindrome, and if not, try deleting index 0, then index 1, all the way up to index n - 1. For each candidate index i, building s[:i] + s[i + 1:] and checking whether it equals its reverse copies and compares roughly n characters.

    Doing O(n) work across n candidate positions takes O(n^2) total operations. When n = 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.

  3. Key idea 1: peel off matching outer ends for free

    Place two index pointers at the outer ends of the string: left = 0 and right = len(s) - 1. Whenever s[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?" Suppose s = "ccac", where s[0] == 'c' and s[3] == 'c' match. Deleting index 0 produces "cac". Because "cac" is a palindrome, its first character (originally at index 1) must equal its last character 'c'. That means s starts with "cc", so deleting index 1 (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.

  4. 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 substring s[left..right]:

    • If we delete neither s[left] nor s[right], any deletion deeper inside leaves s[left] at the front and s[right] at the back — still a mismatch!
    • Therefore, our one and only deletion must remove either s[left] or s[right].
    • Once we spend that deletion, zero deletions remain, so the surviving substring must already be an exact palindrome:
      • Skip left (s[left]): check s[left + 1 .. right].
      • Skip right (s[right]): check s[left .. right - 1].

    Why must we test both choices instead of peeking one character ahead? Look at "aabbaba" after peeling the outer 'a's at indices 0 and 6:

    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.

  5. Write a slice-free helper for exact palindrome checks

    To check whether s[left..right] is an exact palindrome without allocating a new substring, pass s along with inclusive start and end indices left and right. 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 True
    
  6. Write the main two-pointer scan

    Now combine the outer scan with the two candidate range checks. If the while left < right loop finishes without ever hitting a mismatch, the string was already a palindrome (including single-character strings where left == right == 0 right away), so we 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
    
  7. Trace Example 2 step by step

    Let's trace s = "rotatxor" (length 8, indices 0..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 5 leaves "rotator", which is a palindrome.

  8. 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), where n is len(s). Before the first mismatch, left and right look at each outer pair once. At the first mismatch (if any), is_palindrome_range is called at most twice on the unvisited middle segment, so every character in s is 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 string s instead of slicing substrings or building reversed copies.

Edge cases

  • Single character ("z"): left = 0 is not less than right = 0, so the loop never runs and immediately returns True.
  • Two distinct characters ("ab"): Mismatches at (0, 1); is_palindrome_range(s, 1, 1) checks a 1-character slice (left == right) and returns True.
  • Already a palindrome ("racecar", "abba", "aaaa"): Zero deletions are allowed; the outer pointers cross cleanly and return True.
  • Only one side works ("babba" vs "aabbaba"): On "aabbaba", peeking one step ahead suggests both skips look plausible (s[2] == s[5] and s[1] == s[4]), yet only skipping the right character ("aabbaa") produces a palindrome.
  • Needs two or more deletions ("abcdeba", "abcd"): Both skip_left and skip_right hit a second mismatch and return False.
  • 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" where s[left + 1] == s[right] is true by coincidence, causing you to discard the only working branch (skip_right).
  • Calling can_be_palindrome_after_one_deletion recursively on the slices instead of is_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: Allocates O(n) characters per attempt and degrades to O(n^2) time on 100,000-character strings.
  • Off-by-one bounds between inclusive indices and Python half-open slices: In is_palindrome_range(s, left, right), right is inclusive, so skipping left checks (left + 1, right) and skipping right checks (left, right - 1).
  • Returning False when zero deletions are needed: The problem asks for at most one deletion, so an existing palindrome must return True.

Follow-up questions

  • How would you extend the algorithm if up to k character removals are permitted? When k is small (for example k <= 20), you can generalize the exact same idea with recursion can_fix(left, right, remaining_k): advance inward while s[left] == s[right], and on a mismatch try can_fix(left + 1, right, remaining_k - 1) or can_fix(left, right - 1, remaining_k - 1) with memoization (caching (left, right) failures so identical subproblems are never recomputed), which runs in O(n * 2^k) or O(n * k^2) time with banded dynamic programming (solving smaller subproblems in a table to avoid repeated work). For arbitrary large k, find the longest palindromic subsequence (the longest sequence of characters in s that already reads the same both ways without reordering) in O(n^2) time and check whether len(s) - longest_length <= k.
  • What changes if the caller wants the index of a character to remove rather than a boolean? Return -1 (or None, depending on the agreed contract) if the outer scan finishes with no mismatch because zero deletions are needed. At the first mismatch (left, right), return left if is_palindrome_range(s, left + 1, right) is True, else return right if is_palindrome_range(s, left, right - 1) is True, else signal that no single deletion works (for example -2). Clarify tie-breaking with the interviewer since "levmel" can drop either index 2 or index 3.
  • 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 left rightward past non-alphanumeric characters, advance right leftward past non-alphanumeric characters, and compare s[left].lower() == s[right].lower(). Apply the same non-alphanumeric skipping inside is_palindrome_range, keeping time O(n) and extra space O(1).

Follow-up questions

Similar questions

More Whatnot interview questions

All 21 Whatnot questions →