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; achieveO(n)time andO(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,000scontains printable ASCII characters.- Target complexity:
O(len(s))time andO(1)extra space.
Step-by-step walkthrough
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 returnsFalse('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 returnsTrue.
We must solve this in
O(n)time andO(1)extra space.- Spaces and punctuation (
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, butcleanedandcleaned[::-1]each allocate up tonelements in memory —O(n)extra space instead ofO(1).Scan inward from both ends with two pointers
We never need to build
cleanedin memory if we inspect its characters directly insidesfrom both ends at once:- Start
leftat index0andrightatlen(s) - 1. - Whenever
s[left]is not alphanumeric, advanceleftby1to skip over it. - Whenever
s[right]is not alphanumeric, moverightbackward by1to skip over it. - Once both
s[left]ands[right]are alphanumeric, they represent the next mirrored pair of kept characters! Compares[left].lower()ands[right].lower(): if they differ, returnFalse; 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
leftmeets or crossesright(left >= right), every outer pair has matched (and any single middle character automatically matches itself), so we returnTrue.- Start
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 += 1loops without checkingleft < rightinside them — on an all-punctuation string like".,!",leftwalks straight pastlen(s) - 1and crashes withIndexError.Instead, make one single decision per iteration of
while left < right:usingif / elif / else. That way,left < rightis 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 TrueTrace 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 pairsR/r,m/m, and4/4all match while spaces and':'are skipped one by one untilleftandrightmeet on the middle'0'at index4and returnTrue.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!":
- Start at
left = 0('A') andright = 6('!').s[6]is'!'(not alphanumeric), sorightsteps inward to5. - Now
s[0] = 'A'ands[5] = 'a'are both alphanumeric and'a' == 'a', so both pointers advance inward toleft = 1,right = 4. s[1] = '1'ands[4] = '1'match, advancing both toleft = 2(','),right = 3(' ').leftskips','to reach3, whereleft == right == 3ends the loop and returnsTrue.
Complexity
- Time: O(n), where
n = len(s). Every iteration ofwhile left < righteither returnsFalseimmediately or reduces the distanceright - leftby1(on a skip) or2(on a matched pair). Sinceright - leftstarts atn - 1and stops at<= 0, the loop runs at mostntimes withO(1)work per iteration. - Space: O(1) extra space. Only the two integer indexes
leftandrightare 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 < rightis immediatelyFalse, returningTrue. - Only spaces or punctuation (
" ",".,!?"):leftadvances one index per step untilleft == right, returningTrue. - Single alphanumeric character (
"Z",",,7"): Pointers meet on that single character without needing a pair comparison, returningTrue. - Digits mixed with letters (
"0P","1b1"):isalnum()keeps digits ('0'!='p', so"0P"returnsFalse), whereasisalpha()would mistakenly ignore'0'. - Underscores (
"_a"):'_'.isalnum()isFalse, so'_'is properly skipped and"_a"returnsTrue. - 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 underleft < right.
Common mistakes
- Unbounded inner
whileloops for skipping: Writingwhile not s[left].isalnum(): left += 1withoutleft < rightwalks past the end of" -- / -- "and raisesIndexError. Usingif / elifinside a singlewhile left < rightloop prevents this completely. - Using
isalpha()instead ofisalnum(): Drops digits'0'–'9', turning"0P"into"p"(Trueinstead ofFalse). - Filtering with regex
\W(re.sub(r"\W", "", s)): In regular expressions,\wincludes the underscore'_', so"_a"keeps'_'and wrongly returnsFalse(in addition to usingO(n)memory). - Calling
s = s.lower()up front: Allocates a fulln-character copy ofs(O(n)extra space) instead of lowercasing one character at a time. - Allowing a character deletion on the base problem:
"abca"isFalseunder 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 eithers[left]ors[right]: return_is_palindrome_range(s, left + 1, right) or _is_palindrome_range(s, left, right - 1), where_is_palindrome_rangeruns the originalO(1)-space loop on that subarray without further deletions. This checks at most two substrings inO(n)total time andO(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()andlower()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 asunicodedata.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 tradesO(1)extra space for anO(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", a200,000-character string to verify linear speed and zero recursion-depth issues, and randomized strings cross-checked againstcleaned == cleaned[::-1]. Every input finishes inO(n)time because each loop step strictly decreasesright - leftby1or2(or exits immediately) while keeping only two integer indexes inO(1)extra space.
Follow-up questions
- How would you adapt the two-pointer algorithm if removing at most one character from the string were allowed?
- What complications arise when extending this check to arbitrary Unicode text with accents, ligatures, and multi-code-point characters?
- Which boundary inputs would you prioritize in a test suite, and why does the in-place pointer loop stay linear on all of them?
Similar questions
- Count Orthogonal Land Regions
- Largest Sum Without Adjacent Picks
- On-Site Office Laptop Estimation
- Sizing a Retail Customer Parking Lot
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
More Samsung interview questions
- Count Orthogonal Land Regions Easy
- On-Site Office Laptop Estimation Medium
- Largest Sum Without Adjacent Picks Medium Pro
- Sizing a Retail Customer Parking Lot Medium Pro