In-Place Alphanumeric Palindrome Check

Medium · Coding & Algorithms · Machine Learning Engineer · Technical Screen

Problem Statement

Given an input string s, determine whether its letters and digits form the same sequence forward and backward when letter casing is ignored.

Apply the following matching rules in place using two pointers:

  • Keep only alphanumeric characters (ch.isalnum(), i.e., ASCII letters 'a'–'z', 'A'–'Z' and digits '0'–'9'). Skip whitespace, punctuation, underscores ('_'), and other symbols.
  • Compare letters case-insensitively ('A' matches 'a'), while digits must match the exact same digit.
  • If zero or one alphanumeric character remains after skipping symbols, return True.
  • Do not build a filtered or reversed copy of s; achieve O(n) time and O(1) auxiliary memory.

Implement is_valid_palindrome(s: str) -> bool.

Examples

Example 1

Input: s = "Step on no pets!"
Output: True

Ignoring spaces and '!' and normalizing case leaves "steponnopets", which matches character by character from both ends.

Example 2

Input: s = "Rm 404: mr"
Output: True

Keeping letters and digits gives "rm404mr", where 'R'/'r', 'm'/'m', and '4'/'4' pair up symmetrically around the middle '0'.

Example 3

Input: s = "Gate 21, tag"
Output: False

The outer three pairs (g/g, a/a, t/t) match, but the next kept pair compares 'e' with '1', which do not match.

Example 4

Input: s = " -- / -- "
Output: True

Every character is non-alphanumeric, leaving an empty kept sequence that reads identically in both directions.

Constraints

  • 0 <= len(s) <= 200,000
  • s contains printable ASCII characters.
  • Target complexity: O(len(s)) time and O(1) extra space.

Step-by-step walkthrough

  1. Understand what counts as a valid palindrome

    Given a string s, we want to check whether its alphanumeric characters (letters and digits) read the exact same forward and backward when letter case is ignored:

    • Spaces and punctuation (' ', ',', ':', '\'', '_', etc.) are completely ignored.
    • Digits ('0'–'9') are kept alongside letters, so "0P" becomes "0p" and returns False ('0' is not 'p').
    • Uppercase and lowercase letters match, so 'A' matches 'a'.
    • Zero or one kept character (such as "", " ", or ",,a") reads the same in both directions and returns True.

    We must solve this in O(n) time and O(1) extra space.

  2. Why filtering and reversing uses too much memory

    If memory were unlimited, we could build a filtered lowercase list and compare it to its reverse:

    def filter_and_reverse(s: str) -> bool:
        cleaned = [ch.lower() for ch in s if ch.isalnum()]
        return cleaned == cleaned[::-1]
    

    This runs in O(n) time and makes a great reference oracle for testing, but cleaned and cleaned[::-1] each allocate up to n elements in memory — O(n) extra space instead of O(1).

  3. Scan inward from both ends with two pointers

    We never need to build cleaned in memory if we inspect its characters directly inside s from both ends at once:

    • Start left at index 0 and right at len(s) - 1.
    • Whenever s[left] is not alphanumeric, advance left by 1 to skip over it.
    • Whenever s[right] is not alphanumeric, move right backward by 1 to skip over it.
    • Once both s[left] and s[right] are alphanumeric, they represent the next mirrored pair of kept characters! Compare s[left].lower() and s[right].lower(): if they differ, return False; if they match, move both pointers inward (left += 1, right -= 1).
    s:  " R  m     4  0  4  :     m  r "
          ^                          ^
         left=0 ('R') matches right=9 ('r') -> move both inward, skipping spaces & ':'
    

    As soon as left meets or crosses right (left >= right), every outer pair has matched (and any single middle character automatically matches itself), so we return True.

  4. Write a single safe loop (avoiding out-of-bounds skip bugs)

    A very common interview bug is writing nested while not s[left].isalnum(): left += 1 loops without checking left < right inside them — on an all-punctuation string like ".,!", left walks straight past len(s) - 1 and crashes with IndexError.

    Instead, make one single decision per iteration of while left < right: using if / elif / else. That way, left < right is checked before every index access, and neither pointer can ever step out of bounds:

    def is_valid_palindrome(s: str) -> bool:
        # left, right: inward-moving pointers starting at the two ends of `s`
        left = 0
        right = len(s) - 1
    
        # Stop as soon as `left` and `right` meet or cross (`left >= right`).
        while left < right:
            if not s[left].isalnum():
                # Phase 1a: skip one non-alphanumeric character on the left.
                left += 1
            elif not s[right].isalnum():
                # Phase 1b: skip one non-alphanumeric character on the right.
                right -= 1
            elif s[left].lower() != s[right].lower():
                # Phase 2: both point at letters or digits; mismatch ignoring case fails.
                return False
            else:
                # Phase 3: mirrored pair matches; advance both pointers inward.
                left += 1
                right -= 1
    
        return True
    
  5. Trace Example 2, Example 3, and symbol-only strings

    Let's trace the pointers step by step to verify every case:

    Trace 1: s = "Gate 21, tag" (Example 3, length 12)
      left=0 ('G'), right=11 ('g') -> match ('g'=='g') -> left=1, right=10
      left=1 ('a'), right=10 ('a') -> match ('a'=='a') -> left=2, right=9
      left=2 ('t'), right=9  ('t') -> match ('t'=='t') -> left=3, right=8
      left=3 ('e'), right=8  (' ') -> skip right       -> left=3, right=7
      left=3 ('e'), right=7  (',') -> skip right       -> left=3, right=6
      left=3 ('e'), right=6  ('1') -> 'e' != '1'       -> return False!
    
    Trace 2: s = " -- / -- " (Example 4, only spaces and symbols)
      left advances one index per iteration until left == right == 8
      left < right is False (8 < 8) -> loop stops       -> return True!
    

    In Example 2 ("Rm 404: mr"), the pairs R/r, m/m, and 4/4 all match while spaces and ':' are skipped one by one until left and right meet on the middle '0' at index 4 and return True.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def is_valid_palindrome(s: str) -> bool:
        # left, right: inward-moving pointers starting at the two ends of `s`
        left = 0
        right = len(s) - 1
    
        # Stop as soon as `left` and `right` meet or cross (`left >= right`):
        # a single middle character always matches itself, and strict `<` guarantees
        # both indexes stay inside `0 .. len(s) - 1` without extra bounds checks.
        while left < right:
            if not s[left].isalnum():
                # Phase 1a: skip one non-alphanumeric character on the left.
                left += 1
            elif not s[right].isalnum():
                # Phase 1b: skip one non-alphanumeric character on the right.
                right -= 1
            elif s[left].lower() != s[right].lower():
                # Phase 2: both point at letters or digits; mismatch ignoring case fails.
                return False
            else:
                # Phase 3: mirrored pair matches; advance both pointers inward.
                left += 1
                right -= 1
    
        return True
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine checking whether a printed phrase reads the same forward and backward by placing your left finger on the first character and your right finger on the last character — an application of the two-pointer technique (traversing a sequence in place using two integer indexes instead of allocating modified copies). Whenever either finger rests on a space or punctuation mark, you slide just that finger one character inward to ignore it. Whenever both fingers land on letters or digits, you check whether they match (ignoring uppercase vs lowercase); if they match, both fingers step inward together until they meet in the middle.

The obvious two-line approach — building a cleaned string of lowercase alphanumeric characters and checking cleaned == cleaned[::-1] — gets the right answer, but creating the filtered string and its reversed copy consumes O(n) extra memory, violating the strict O(1) extra-space constraint. Recursive two-pointer solutions also fail on long inputs because each inward step adds a stack frame (O(n) stack memory, hitting Python's ~1,000-call recursion limit). Skipping and comparing in place inside a single while left < right loop uses only two integers regardless of string length.

Walk through a compact 7-character example, s = "A1, 1a!":

  1. Start at left = 0 ('A') and right = 6 ('!'). s[6] is '!' (not alphanumeric), so right steps inward to 5.
  2. Now s[0] = 'A' and s[5] = 'a' are both alphanumeric and 'a' == 'a', so both pointers advance inward to left = 1, right = 4.
  3. s[1] = '1' and s[4] = '1' match, advancing both to left = 2 (','), right = 3 (' '). left skips ',' to reach 3, where left == right == 3 ends the loop and returns True.

Complexity

  • Time: O(n), where n = len(s). Every iteration of while left < right either returns False immediately or reduces the distance right - left by 1 (on a skip) or 2 (on a matched pair). Since right - left starts at n - 1 and stops at <= 0, the loop runs at most n times with O(1) work per iteration.
  • Space: O(1) extra space. Only the two integer indexes left and right are kept across iterations (s[left].lower() creates at most a temporary 1-character string that is immediately discarded), with no filtered copy, slice, or recursion stack.

Edge cases

  • Empty string (""): left = 0, right = -1; left < right is immediately False, returning True.
  • Only spaces or punctuation (" ", ".,!?"): left advances one index per step until left == right, returning True.
  • Single alphanumeric character ("Z", ",,7"): Pointers meet on that single character without needing a pair comparison, returning True.
  • Digits mixed with letters ("0P", "1b1"): isalnum() keeps digits ('0' != 'p', so "0P" returns False), whereas isalpha() would mistakenly ignore '0'.
  • Underscores ("_a"): '_'.isalnum() is False, so '_' is properly skipped and "_a" returns True.
  • Odd vs even kept counts: Even counts compare every pair and cross (left > right); odd counts leave the middle kept character untouched (left == right). Both stop cleanly under left < right.

Common mistakes

  • Unbounded inner while loops for skipping: Writing while not s[left].isalnum(): left += 1 without left < right walks past the end of " -- / -- " and raises IndexError. Using if / elif inside a single while left < right loop prevents this completely.
  • Using isalpha() instead of isalnum(): Drops digits '0'–'9', turning "0P" into "p" (True instead of False).
  • Filtering with regex \W (re.sub(r"\W", "", s)): In regular expressions, \w includes the underscore '_', so "_a" keeps '_' and wrongly returns False (in addition to using O(n) memory).
  • Calling s = s.lower() up front: Allocates a full n-character copy of s (O(n) extra space) instead of lowercasing one character at a time.
  • Allowing a character deletion on the base problem: "abca" is False under strict matching; one-character deletion applies only when explicitly requested as a follow-up.

Follow-up questions

  • How would you adapt the two-pointer algorithm if removing at most one character from the string were allowed? Run the exact same two-pointer scan until the first alphanumeric mismatch at (left, right). Because all characters outside [left, right] already matched (and deleting an ignored punctuation mark changes nothing), the single allowed deletion must remove either s[left] or s[right]: return _is_palindrome_range(s, left + 1, right) or _is_palindrome_range(s, left, right - 1), where _is_palindrome_range runs the original O(1)-space loop on that subarray without further deletions. This checks at most two substrings in O(n) total time and O(1) extra space.
  • What complications arise when extending this check to arbitrary Unicode text with accents, ligatures, and multi-code-point characters? Code-point-by-code-point isalnum() and lower() break on general Unicode in three ways: first, "e\u0301" ('e' + combining acute accent) has a non-alphanumeric combining mark that gets stripped unless you first apply Unicode normalization (converting canonically equivalent sequences to a single standard form such as unicodedata.normalize("NFC", s)). Second, pairing must operate on grapheme clusters (user-perceived characters that may span multiple Unicode code points, such as base letter + combining marks) rather than raw code points. Third, Unicode case-insensitivity requires casefolding (str.casefold(), an aggressive locale-independent normalization that maps ligatures/letters like German 'ß' to "ss" for caseless matching), and because normalization and casefolding can change string length, full Unicode support typically trades O(1) extra space for an O(n) normalized buffer alongside a clear product spec for accents and non-ASCII digits (like '²').
  • Which boundary inputs would you prioritize in a test suite, and why does the in-place pointer loop stay linear on all of them? Include the empty string "", symbol-only " -- / -- ", single kept characters "a" and ",,7", mixed case "AbBA", digit-letter mismatches "0P", underscores "_a", near-palindromes "abca", a 200,000-character string to verify linear speed and zero recursion-depth issues, and randomized strings cross-checked against cleaned == cleaned[::-1]. Every input finishes in O(n) time because each loop step strictly decreases right - left by 1 or 2 (or exits immediately) while keeping only two integer indexes in O(1) extra space.

Follow-up questions

Similar questions

More Samsung interview questions

All 5 Samsung questions →