Single-Pass S-Expression Parser with Error Positions
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Build a streaming-cursor parser for a compact Lisp-like S-expression syntax in three incremental milestones: standalone atoms, flat parenthesized lists, and arbitrarily nested lists.
Your parser must scan the input string once from left to right using an integer index cursor. Pre-tokenizing the entire string with str.split(), regular expressions, or global substring replacements is not allowed. Whenever the input violates the grammar, parsing must halt immediately at the earliest offending character offset and raise ParseError without returning a partial syntax tree.
Lexical & Grammar Rules
- Delimiters (ASCII whitespace): space (
' '), horizontal tab ('\t'), carriage return ('\r'), and newline ('\n') separate adjacent elements and may appear before or after the single top-level expression. - Integer atom (
int): an optional leading minus sign ('-') followed directly by at least one ASCII digit ('0'–'9'), evaluated as a Pythonint(such as-24or009->9). - Symbol atom (
str): begins with an ASCII letter ('a'–'z','A'–'Z') or an operator character from+ - * / _, followed by zero or more ASCII letters, ASCII digits ('0'–'9'), or+ - * / _characters (such asscale_by,-,-k, or*). Any token satisfying the integer rule is always classified as anintrather than a symbolstr. - Parenthesized list (
list): opens with'(', contains zero or more whitespace-separated expressions (which in Milestone 3 may themselves be nested lists), and closes with')', producing a Pythonlist. Opening and closing parentheses terminate an adjacent atom without requiring intervening whitespace, so(neg(y))evaluates to["neg", ["y"]]. - Illegal tokens:
- Characters outside ASCII whitespace,
'(',')', ASCII letters, ASCII digits, and+ - * / _(for instance'$','#','"', or non-ASCII characters like'é'and'²') are always illegal. - A token whose initial character is an ASCII digit (
'0'–'9') cannot contain any non-digit atom characters (for instance85kor4-1).
- Characters outside ASCII whitespace,
- Top-level framing: valid input contains one complete expression with optional leading/trailing ASCII whitespace. Empty or blank strings and any extra non-whitespace characters after the root expression are rejected.
Required Functions & ParseError Contract
Keep the ParseError(kind, message, index) exception class and function signatures from starter.py:
read_atom(text: str, pos: int) -> Tuple[Union[int, str], int](Milestone 1): reads a single atom starting right attext[pos]and returns(parsed_atom, next_pos)wherenext_posis the first index after the atom.parse_atom(text: str) -> Union[int, str](Milestone 1): parses an entire input string holding one atom (plus optional outer whitespace).parse(text: str)(Milestones 2 & 3): parses an entire input string holding one expression (an atom or a flat/nested list).
Every syntax failure must raise ParseError with the exact kind and 0-based character index below:
kind |
Trigger condition | index reported |
|---|---|---|
"invalid_char" |
Encountered a character forbidden everywhere in the grammar | Offset of that illegal character |
"bad_number" |
Atom started with '0'–'9' and hit a non-digit atom character |
Offset of that first non-digit character |
"expected_atom" |
read_atom / parse_atom started on '(', ')', whitespace, or end-of-string |
Start offset passed to read_atom |
"unexpected_end" |
Input ended (or had only whitespace) before an expression started | len(text) |
"unclosed_list" |
Input ended before an open '(' found its matching ')' |
Offset of the innermost unmatched '(' |
"unexpected_close" |
Found ')' at a position where an expression was expected to start |
Offset of that ')' |
"trailing_input" |
Non-whitespace character appeared after the completed root expression | Offset of that first extra character |
Examples
Example 1
Input:
parse_atom(" -24\n")
parse_atom("scale_by")
read_atom("(sub 90)", 1)
parse_atom("85k")
Output:
-24
"scale_by"
("sub", 4)
raises ParseError(kind="bad_number", index=2)
Walk-through: Leading spaces and the trailing newline around -24 are skipped, producing integer -24. scale_by begins with a letter and uses only legal ASCII symbol characters, returning "scale_by". Calling read_atom("(sub 90)", 1) scans from index 1 up to the space at index 4 and returns ("sub", 4). In "85k", index 0 is a digit ('8'), so 'k' at index 2 immediately raises "bad_number" at index 2.
Example 2
Input: text = "(let (val -8) (* val 3))"
Output: ["let", ["val", -8], ["*", "val", 3]]
Walk-through: The outer list opens at index 0, reads symbol "let", recursively reads the two-element inner list ["val", -8] (indices 5..12) and the three-element inner list ["*", "val", 3] (indices 14..22), and closes at index 23. Adjacent parentheses without spaces also work: parse("(neg(y))") returns ["neg", ["y"]], and parse("()") returns [].
Example 3
Input:
parse("(sum (mul 4 $ 5) 9)")
parse("(cat (dog (fox)")
parse("(inc 1) 2")
Output:
raises ParseError(kind="invalid_char", index=12)
raises ParseError(kind="unclosed_list", index=5)
raises ParseError(kind="trailing_input", index=8)
Walk-through: In "(sum (mul 4 $ 5) 9)", scanning halts at '$' (index 12) with "invalid_char". In "(cat (dog (fox)" (length 15), the deepest list opened at index 10 closes at index 14, leaving the '(' at index 5 as the innermost still-open list when the string ends, so "unclosed_list" points to index 5. In "(inc 1) 2", the root list finishes after ')' at index 6, so '2' at index 8 triggers "trailing_input".
Constraints
0 <= len(text) <= 5 * 10^5- Valid inputs run in
O(len(text))time andO(len(text))total memory withoutstr.split(), regexes, orO(n^2)string slicing. - Only ASCII characters defined by the lexical rules are valid; Unicode digits/letters such as
'²'or'é'must raise"invalid_char". - Standard recursion depth (up to several hundred nested lists) is sufficient for
parse(text).
Step-by-step walkthrough
Pin down the grammar and error contract
An S-expression (symbolic expression) is a minimalist Lisp-style notation in which every piece of data is either a single atom (such as
-24orscale_by) or a parenthesized list of smaller expressions (such as(let (val -8) (* val 3))).Before writing any code, settle the open interface choices so every edge case has one unambiguous behavior:
- Errors raise an exception (
ParseError) immediately: if anything violates the grammar, scanning halts at the earliest bad offset and never returns a half-built structure. - No string literals in the base language (covered in the follow-up questions).
- Zero-based character offset pinpoints every syntax problem.
- One root expression per string: any non-whitespace character after that root expression finishes raises
trailing_input.
Give each failure mode a machine-testable
kindand decide the exact character index it must report:kind when it happens index points to ----------------- -------------------------------------------------- ------------------------- invalid_char a character forbidden everywhere ('$', '"', 'é') that bad character bad_number an atom starting with 0-9 hits a non-digit that first non-digit expected_atom read_atom / parse_atom sees '(' or ')' at start that parenthesis unexpected_end input ends before an expected expression begins len(text) unclosed_list input ends while a '(' is still waiting for ')' the innermost open '(' unexpected_close ')' appears where a new expression must begin that ')' trailing_input non-whitespace appears after root expression ends that extra character- Errors raise an exception (
Key idea: advance a single integer cursor instead of splitting
Pre-splitting with
text.split()is disallowed—and even if it were permitted, it would break the parser:"(neg(y))"has zero spaces yet holds six syntactic pieces, and whole-string splitting discards the character offsets needed to report that"(uv$)"failed at index3.Instead, advance one integer cursor
posmonotonically from0tolen(text). Every reader routine obeys the same contract:reader(text, pos) --> (parsed_value, next_pos)Here
posis where the routine starts reading insidetext, andnext_posis the index right after the characters it consumed:text: ( s u b 9 ( a b s y ) ) index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ^-------^ ^-----------------^ read_atom(1) read_list(7) -> ("sub", 4) -> (["abs", "y"], 14)Because
textis never copied or re-sliced ahead of time,posis always the true global character index, and each character is visited only a constant number of times (O(n)total work).Milestone 1: scan and classify one atom in a single pass
An atom begins at
text[pos]and ends as soon as the cursor meets ASCII whitespace,'(',')', or the end oftext. While stepping forward character by character, two checks catch atom failures at the exact offending offset:- If
chis neither a delimiter nor in our ASCII atom alphabet (ATOM_CHARS), raiseinvalid_charatpos. - If the initial character
text[start]was an ASCII digit (0–9), every subsequent character in the atom must also be an ASCII digit—otherwise raisebad_numberright atpos(so"85k"fails at'k', index2).
Define explicit ASCII character strings (
DIGITS,LETTERS) rather than calling Python's built-instr.isdigit()orstr.isalpha(). Python's string methods accept Unicode characters such as superscript'²'as digits and'é'as letters, whereas our specification restricts atoms to ASCII.Once scanning consumes at least one character (
pos > start),is_integertests whethertext[start:pos]is an optional'-'followed by one or more ASCII digits. That converts"-24"into-24, while keeping"-","-k", and"scale_by"as symbol strings:from typing import List, Tuple, Union # Explicit ASCII character sets: Python's str.isdigit()/str.isalpha() accept Unicode # characters like '²' or 'é', whereas our S-expression grammar permits ASCII only. WHITESPACE = " \t\r\n" DIGITS = "0123456789" LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" SYMBOL_EXTRA = "+-*/_" ATOM_CHARS = LETTERS + DIGITS + SYMBOL_EXTRA class ParseError(Exception): """A parse failure: `kind` names the problem, `index` is the 0-based character index. kinds: "invalid_char", "bad_number", "expected_atom", "unexpected_end", "unclosed_list", "unexpected_close", "trailing_input". """ def __init__(self, kind: str, message: str, index: int): super().__init__(f"{message} (index {index})") self.kind = kind self.message = message self.index = index def is_integer(token: str) -> bool: """Return True if `token` is an optional '-' followed by one or more ASCII digits.""" # Strip a single leading minus sign; a lone "-" leaves "" and stays a symbol if token.startswith("-"): digits = token[1:] else: digits = token if digits == "": return False for ch in digits: if ch not in DIGITS: return False return True def to_value(token: str) -> Union[int, str]: """Convert a validated atom slice into a Python int (if integer) or str (if symbol).""" if is_integer(token): return int(token) return token def read_atom(text: str, pos: int) -> Tuple[Union[int, str], int]: """Part 1: read one atom starting at `text[pos]` and return `(value, next_pos)`.""" start = pos while pos < len(text): ch = text[pos] # Whitespace or any parenthesis cleanly ends the current atom without consuming it if ch in WHITESPACE or ch == "(" or ch == ")": break # Stop at the exact index of any character outside the legal ASCII atom alphabet if ch not in ATOM_CHARS: raise ParseError("invalid_char", f"invalid character {ch!r}", pos) # A token starting with a digit must be all digits (reject e.g. "85k" at 'k') if text[start] in DIGITS and ch not in DIGITS: raise ParseError("bad_number", f"malformed number: {ch!r} cannot follow a digit", pos) pos += 1 # Zero characters consumed means `pos` sat on '(' , ')' , whitespace, or end-of-string if pos == start: raise ParseError("expected_atom", "expected an atom", start) token = text[start:pos] return to_value(token), pos- If
Milestone 1: wrap the atom reader for a full-string input
To parse a whole-string atom in
parse_atom(text), write two small cursor utilities that Milestones 2 and 3 also share:skip_whitespace(text, pos)advancesposacross spaces, tabs, carriage returns, and newlines.check_nothing_left(text, pos)skips trailing whitespace after the root expression and raisestrailing_inputif any character remains (catching"u v"at index2).
def skip_whitespace(text: str, pos: int) -> int: """Advance cursor `pos` past any ASCII whitespace and return the new index.""" while pos < len(text) and text[pos] in WHITESPACE: pos += 1 return pos def check_nothing_left(text: str, pos: int) -> None: """Ensure only whitespace follows the completed top-level expression.""" pos = skip_whitespace(text, pos) if pos < len(text): raise ParseError("trailing_input", f"unexpected {text[pos]!r} after the expression", pos) def parse_atom(text: str) -> Union[int, str]: """Part 1: parse an entire input string containing exactly one atom.""" pos = skip_whitespace(text, 0) if pos == len(text): raise ParseError("unexpected_end", "expected an atom, found end of input", pos) value, pos = read_atom(text, pos) check_nothing_left(text, pos) return valueNotice how
" "behaves:skip_whitespacemovesposfrom0to3(len(text)), andparse_atomraisesunexpected_endat index3.Milestone 2: read a parenthesized list and isolate every error point
Once
read_liststeps past an opening'('recorded atopen_index, it loops to collect elements. At the start of each iteration, after advancing past whitespace, only three cases exist:what sits at text[pos]? meaning what read_list does -------------------------- ------------------------------- -------------------------------------- pos == len(text) string ended before ')' raise unclosed_list at open_index text[pos] == ')' current list is complete return (items, pos + 1) any other character start of the next child item call read_expr(text, pos) and appendEvery error class now has one dedicated check:
invalid_charandbad_number: insideread_atomunclosed_list: at the top ofread_list's loop whenpos == len(text)unexpected_close: insideread_exprwhen')'sits where an expression must begin (e.g.,parse(")"))unexpected_end: insideread_exprwhen the whole string is empty or blanktrailing_input: insidecheck_nothing_leftonce the root expression completes (e.g.,"(inc 1) 2"at8, or"(u))"at3)
def read_expr(text: str, pos: int): """Read one expression (atom or list) starting at or after `pos`; return `(value, next_pos)`.""" pos = skip_whitespace(text, pos) if pos == len(text): raise ParseError("unexpected_end", "expected an expression, found end of input", pos) ch = text[pos] if ch == "(": return read_list(text, pos) # A ')' here has no matching '(' expecting an element, or sits at top level if ch == ")": raise ParseError("unexpected_close", "unexpected ')'", pos) return read_atom(text, pos) def read_list(text: str, pos: int) -> Tuple[List, int]: """Read a parenthesized list starting at `text[pos] == '('`; return `(items, next_pos)`.""" # Remember where '(' appeared so an unclosed error points to the innermost open '(' open_index = pos pos += 1 # items: Python list of parsed elements (ints, symbol strs, or nested lists) items = [] while True: pos = skip_whitespace(text, pos) if pos == len(text): raise ParseError("unclosed_list", "'(' is never closed", open_index) if text[pos] == ")": # Step past ')' and hand the updated cursor back to the caller return items, pos + 1 value, pos = read_expr(text, pos) items.append(value)Milestone 3: unlock arbitrary nesting via mutual recursion
Because
read_exprdelegates'('toread_list, andread_listcallsread_exprfor every child item, the two routines form mutual recursion (two functions calling each other to traverse nested structure). That handles nested lists to arbitrary depth automatically:- How does an inner list hand back control? The inner
read_listconsumes up through its closing')'and returnspos + 1. The enclosingread_listresumes itswhileloop right at that updatedpos. - Which
'('gets reported on premature end-of-input? Each activeread_listcall keeps its ownopen_indexlocal variable. If the string ends mid-parse, execution is inside the deepest openread_listframe, which raisesunclosed_listwith its ownopen_index—reporting the innermost unmatched'('. - How deep can Python's call stack go? Each nested
'('uses two call frames (read_expr+read_list), so Python's default1,000-frame limit comfortably supports ~500nested levels (and the follow-up section replaces recursion with an explicit heap list for100,000+levels).
Now
parse(text)simply reads one root expression from index0and verifies that only whitespace trails it:def parse(text: str): """Parts 2 and 3: parse a single top-level S-expression (atom or arbitrarily nested list).""" value, pos = read_expr(text, 0) check_nothing_left(text, pos) return value- How does an inner list hand back control? The inner
Trace Example 2 and Example 3 step by step
First trace
"(neg(y))"(indices0..7) from Example 2 to see how parentheses delimit atoms with zero spaces:pos char active call & action --- ------ --------------------------------------------------------------- 0 '(' read_list #1 starts (open_index = 0), advances pos -> 1 1 'n'..'g' read_atom(1) scans "neg", stops at '(' at index 4 -> ("neg", 4) 4 '(' read_list #2 starts (open_index = 4), advances pos -> 5 5 'y' read_atom(5) scans 'y', stops at ')' at index 6 -> ("y", 6) 6 ')' read_list #2 finishes -> returns (["y"], 7) to read_list #1 7 ')' read_list #1 finishes -> returns (["neg", ["y"]], 8) to parse 8 end check_nothing_left(8) sees end of string -> returns ["neg", ["y"]]Next trace the unclosed nested expression
"(cat (dog (fox)"(length15, indices0..14) from Example 3:index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 text: ( c a t ( d o g ( f o x ) pos token open '(' stack what happens ----- ----- --------------- ---------------------------------------------------------- 0 '(' [0] open list #1 at index 0 1..3 "cat" [0] append "cat" to list #1 5 '(' [0, 5] open list #2 at index 5 6..8 "dog" [0, 5] append "dog" to list #2 10 '(' [0, 5, 10] open list #3 at index 10 11..13 "fox" [0, 5, 10] append "fox" to list #3 14 ')' [0, 5] close list #3 -> ["fox"] appended to list #2; pos -> 15 15 end [0, 5] list #2 sees pos == 15 -> ParseError("unclosed_list", 5)List
#3(opened at10) closed cleanly at14, leaving list#2(opened at5) as the innermost open list when the string runs out—soParseErrorreports index5.Complete solution
from typing import List, Tuple, Union # Explicit ASCII character sets: Python's str.isdigit()/str.isalpha() accept Unicode # characters like '²' or 'é', whereas our S-expression grammar permits ASCII only. WHITESPACE = " \t\r\n" DIGITS = "0123456789" LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" SYMBOL_EXTRA = "+-*/_" ATOM_CHARS = LETTERS + DIGITS + SYMBOL_EXTRA class ParseError(Exception): """A parse failure: `kind` names the problem, `index` is the 0-based character index. kinds: "invalid_char", "bad_number", "expected_atom", "unexpected_end", "unclosed_list", "unexpected_close", "trailing_input". """ def __init__(self, kind: str, message: str, index: int): super().__init__(f"{message} (index {index})") self.kind = kind self.message = message self.index = index def skip_whitespace(text: str, pos: int) -> int: """Advance cursor `pos` past any ASCII whitespace and return the new index.""" while pos < len(text) and text[pos] in WHITESPACE: pos += 1 return pos def is_integer(token: str) -> bool: """Return True if `token` is an optional '-' followed by one or more ASCII digits.""" # Strip a single leading minus sign; a lone "-" leaves "" and stays a symbol if token.startswith("-"): digits = token[1:] else: digits = token if digits == "": return False for ch in digits: if ch not in DIGITS: return False return True def to_value(token: str) -> Union[int, str]: """Convert a validated atom slice into a Python int (if integer) or str (if symbol).""" if is_integer(token): return int(token) return token def read_atom(text: str, pos: int) -> Tuple[Union[int, str], int]: """Part 1: read one atom starting at `text[pos]` and return `(value, next_pos)`.""" start = pos while pos < len(text): ch = text[pos] # Whitespace or any parenthesis cleanly ends the current atom without consuming it if ch in WHITESPACE or ch == "(" or ch == ")": break # Stop at the exact index of any character outside the legal ASCII atom alphabet if ch not in ATOM_CHARS: raise ParseError("invalid_char", f"invalid character {ch!r}", pos) # A token starting with a digit must be all digits (reject e.g. "85k" at 'k') if text[start] in DIGITS and ch not in DIGITS: raise ParseError("bad_number", f"malformed number: {ch!r} cannot follow a digit", pos) pos += 1 # Zero characters consumed means `pos` sat on '(' , ')' , whitespace, or end-of-string if pos == start: raise ParseError("expected_atom", "expected an atom", start) token = text[start:pos] return to_value(token), pos def check_nothing_left(text: str, pos: int) -> None: """Ensure only whitespace follows the completed top-level expression.""" pos = skip_whitespace(text, pos) if pos < len(text): raise ParseError("trailing_input", f"unexpected {text[pos]!r} after the expression", pos) def parse_atom(text: str) -> Union[int, str]: """Part 1: parse an entire input string containing exactly one atom.""" pos = skip_whitespace(text, 0) if pos == len(text): raise ParseError("unexpected_end", "expected an atom, found end of input", pos) value, pos = read_atom(text, pos) check_nothing_left(text, pos) return value def read_expr(text: str, pos: int): """Read one expression (atom or list) starting at or after `pos`; return `(value, next_pos)`.""" pos = skip_whitespace(text, pos) if pos == len(text): raise ParseError("unexpected_end", "expected an expression, found end of input", pos) ch = text[pos] if ch == "(": return read_list(text, pos) # A ')' here has no matching '(' expecting an element, or sits at top level if ch == ")": raise ParseError("unexpected_close", "unexpected ')'", pos) return read_atom(text, pos) def read_list(text: str, pos: int) -> Tuple[List, int]: """Read a parenthesized list starting at `text[pos] == '('`; return `(items, next_pos)`.""" # Remember where '(' appeared so an unclosed error points to the innermost open '(' open_index = pos pos += 1 # items: Python list of parsed elements (ints, symbol strs, or nested lists) items = [] while True: pos = skip_whitespace(text, pos) if pos == len(text): raise ParseError("unclosed_list", "'(' is never closed", open_index) if text[pos] == ")": # Step past ')' and hand the updated cursor back to the caller return items, pos + 1 value, pos = read_expr(text, pos) items.append(value) def parse(text: str): """Parts 2 and 3: parse a single top-level S-expression (atom or arbitrarily nested list).""" value, pos = read_expr(text, 0) check_nothing_left(text, pos) return value✅ Submit now — all tests should pass.
Intuition & how it works
Think of parsing an S-expression—a Lisp-style notation built from single atoms (such as -24 or scale_by) and parenthesized lists (such as (let (val -8) (* val 3)))—like sliding your index finger across a line of text from left to right. Your finger (pos) never backs up and never chops the string into pieces ahead of time: whenever it lands on '(', you open a new container for a list, fill that container with whatever atoms or nested containers follow until your finger reaches the matching ')', and return both the finished container and your finger's updated offset.
The tempting shortcut—padding parentheses with spaces and calling text.split()—violates the single-pass rule and ruins error reporting anyway. Pre-splitting destroys the original character offsets (making it impossible to report that "(uv$)" failed at index 3), allocates extra intermediate strings, and scans past early errors instead of halting immediately. Even in a hand-rolled scanner, grabbing a whole token before inspecting its characters fails on "85k$", which violated the integer rule at 'k' (index 2) before ever reaching '$' (index 3).
Walk through "(op (sub 9))" (12 characters, indices 0..11) to see the shared cursor (value, next_pos) in action:
pos = 0sees'(', soread_listsavesopen_index = 0and stepsposto1.pos = 1callsread_atom, which scans"op", stops at the space at3, and returns("op", 3).- After skipping the space,
pos = 4sees'(', opening a nestedread_list(open_index = 4) that reads"sub"(pos = 5..8) and integer9(pos = 9..10), hits')'atpos = 10, and returns(["sub", 9], 11). - Finally, the outer
read_listsees')'atpos = 11, returns(["op", ["sub", 9]], 12), andcheck_nothing_leftconfirms index12is the end of the string.
Complexity
- Time: O(n) for an input string of
ncharacters. The integer cursorposonly advances forward from0ton, and each character is inspected a small constant number of times—once when advancingposinskip_whitespaceorread_atom, and at most twice more when slicingtext[start:pos]and runningis_integer/int(token). (Caveat: CPython's base-10int()conversion is quadratic on multi-thousand-digit numbers, which is why Python 3.11+ capsint(str)at 4,300 digits by default.) - Space: O(n + d), which simplifies to O(n) because nesting depth
d <= n. Storing the output tree of atoms and lists usesO(n)memory in the input size, while mutual recursion (two functions calling each other) uses two Python call-stack frames (read_exprandread_list) per open parenthesis—O(d)stack space, supporting roughly500nested levels under Python's default1,000-frame recursion limit.
Edge cases
- Empty or whitespace-only input:
""fails withunexpected_endat index0;" "advances past the spaces and fails withunexpected_endat index3(len(text)). - Minus signs vs. negative numbers:
"-24"is the integer-24, whereas"-","-k", and"+"are valid symbol strings. Under the stated lexical rules,"+5"and"-7z"begin with+or-and contain legal symbol characters without matching the integer rule, so they parse as symbols—worth noting aloud to your interviewer in case they prefer rejecting them. - Leading zeros and
-0:"009"parses to9and"-0"parses to0. - Parentheses touching atoms:
"(neg(y))"and"(34(m))"parse cleanly to["neg", ["y"]]and[34, ["m"]]because'('and')'end an atom without consuming themselves. - Non-ASCII characters (
'²','é'): rejected withinvalid_charbecause membership is checked against explicit ASCII sets rather thanstr.isdigit()(which returnsTruefor'²') orint()(which accepts Unicode decimal digits). - Multiple errors in one string:
"(u $ (v"halts right at'$'and raisesinvalid_charat index3, never reaching the unclosed'('at index5. - Stray closing parentheses:
")"at the start of an expression raisesunexpected_closeat0, whereas"(u))"completes the valid root list["u"]at index3and raisestrailing_inputon the extra')'at index3. - Multi-thousand-digit integers: Python raises
ValueErrorwhenint()exceeds 4,300 digits (sys.set_int_max_str_digits); in production code, catchValueErroraroundint(token)and wrap it inParseError("bad_number", ..., start)so callers only ever handleParseError.
Common mistakes
- Calling
text.split()or regex replacement (text.replace("(", " ( ")), which breaks the one-pass cursor rule and loses original character indices. - Passing string slices (
read_expr(text[pos:])) on recursive calls—takingO(n^2)time on deep inputs and resetting offsets to0inside every slice so reported error indices are wrong. - Scanning to the next delimiter first and validating the token afterward, causing
"85k$"to blame index3('$') even though the number broke at index2('k'). - Forgetting that
'('and')'terminate an atom, causing"(y)"to absorb')'into symbol"y)"and falsely report an unclosed list. - Checking for trailing characters only after
read_listand missingparse_atom("u v")orparse("y z"). - Using
str.isdigit()andstr.isalpha(), silently accepting Unicode superscripts and accented letters as ASCII tokens. - Reporting
len(text)as the error offset forunclosed_listinstead of recordingopen_indexat the'('that remained open.
Follow-up questions
- Suppose a caller passes 100,000 levels of nested parentheses and triggers a stack overflow. How can you eliminate recursion while keeping every output and error identical? Replace Python's call stack with an explicit heap stack—a Python list
stackwhere each open'('pushes[items_list, open_index]. Every branch ('(',')', atom, end-of-input, and trailing check) mirrorsread_exprandread_liststep for step, producing identical syntax trees and raising the exact same(kind, index)ParseErroron every input while running inO(n)heap memory with no recursion ceiling:
def parse_iterative(text: str):
# stack: list of [items_so_far, open_paren_index], innermost open '(' last
stack = []
pos = 0
while True:
pos = skip_whitespace(text, pos)
if pos == len(text):
if stack:
raise ParseError("unclosed_list", "'(' is never closed", stack[-1][1])
raise ParseError("unexpected_end", "expected an expression, found end of input", pos)
ch = text[pos]
if ch == "(":
stack.append([[], pos])
pos += 1
continue
if ch == ")":
if not stack:
raise ParseError("unexpected_close", "unexpected ')'", pos)
value = stack.pop()[0]
pos += 1
else:
value, pos = read_atom(text, pos)
if not stack:
break # Completed the single top-level expression
stack[-1][0].append(value)
check_nothing_left(text, pos)
return value
-
What changes are needed to support double-quoted strings containing whitespace, parentheses, and backslash escapes? Add
if ch == '"': return read_string(text, pos)insideread_expr.read_stringsavesopen_quote = pos, advances topos + 1, and accumulates characters until an unescaped'"': spaces and parentheses inside quotes are copied literally (yet another reasonsplit()parsers break on strings), while'\\'checks the next character to decode'\\"','\\\\','\\n', and'\\t'—raisingbad_escapeat the backslash for unknown escapes orunclosed_stringatopen_quoteifposreacheslen(text). Also require a delimiter (whitespace,'(',')', or end of input) immediately after the closing quote so"uv"wfails cleanly, and wrap either symbols (Symbol("y")) or strings in a distinct type so string"y"and symbolystay distinguishable. -
If S-expressions arrive incrementally over a socket in arbitrary byte chunks, how would you redesign the parser to pause and resume cleanly? Recursive functions trap parser state inside Python stack frames that cannot suspend mid-atom when a TCP packet splits
"24"and"9". Refactor into a stateful push parser class storing:stackof open[items, open_index]frames, atoken_bufstring andtoken_startoffset for any atom currently being scanned, a cumulativeglobal_offsetacross chunks, and an incremental UTF-8 decoder (codecs.getincrementaldecoder("utf-8")()) in case a multi-byte sequence spans two packets. Callingfeed(chunk)consumes characters and emits finished root expressions while holding any trailing unfinished atom intoken_buf(since the next chunk could extend it); callingfinish()at EOF flushes any buffered atom and raisesunclosed_listorunexpected_endif open frames remain. -
How can your parser report 1-based line and column coordinates on failure instead of a raw character offset? Keep advancing the single integer
poson the hot path so valid inputs pay zero extra cost, and convertindexto 1-based(line, column)lazily only when constructing aParseError. For instance, in"(u\n $)",'$'sits at index5: counting"\n"before index5yieldsline = 1 + 1 = 2, and measuring from just past the last newline at index2yieldscolumn = 5 - 3 + 1 = 3. Clarify edge rules up front (1-based vs. 0-based, normalizing"\r\n", and counting code points vs. bytes or tab stops); if batch diagnostics ever format hundreds of errors on one file, prebuild a sorted list of newline offsets once and query it withbisect.
def line_and_column(text: str, index: int) -> Tuple[int, int]:
"""Convert a 0-based character index into 1-based (line, column) using '\\n' line breaks."""
line = text.count("\n", 0, index) + 1
last_newline = text.rfind("\n", 0, index)
column = index - (last_newline + 1) + 1
return line, column
Alternative approaches
- Generator-based lexer + parser: write a
tokenize(text)generator (a routine thatyields one(kind, text, index)token on demand, still in one pass without materializing a token array) and consume it from the parser. Separating lexical rules from tree construction pays off once the language adds string literals,;comments, and quote reader macros ('y), though for this compact grammar direct cursor functions are shorter and clearer. - Explicit stack from the start: using
parse_iterativedirectly asparseremoves the ~500-level call-stack ceiling immediately, with the minor trade-off that mutual recursion (read_expr<->read_list) mirrors the recursive grammar rule almost line for line.
Follow-up questions
- Suppose a caller passes 100,000 levels of nested parentheses and triggers a stack overflow. How can you eliminate recursion while keeping every output and error identical?
- What changes are needed to support double-quoted strings containing whitespace, parentheses, and backslash escapes?
- If S-expressions arrive incrementally over a socket in arbitrary byte chunks, how would you redesign the parser to pause and resume cleanly?
- How can your parser report 1-based line and column coordinates on failure instead of a raw character offset?
Similar questions
- Crash-Safe Log-Structured Key-Value Engine
- Bounded Thread-Pool Batch Executor
- XorShift32 Stream Cipher for Tree Documents
- Noisy Pod Alert Normalization and Outlier Replica Detection
- Multi-Tenant LLM Serving and Scheduling Platform
- Distributed Log Ingestion and Search Platform
More Baseten interview questions
- Distributed Log Ingestion and Search Platform Medium
- XorShift32 Stream Cipher for Tree Documents Medium
- Crash-Safe Log-Structured Key-Value Engine Hard Pro
- Noisy Pod Alert Normalization and Outlier Replica Detection Medium Pro
- Multi-Tenant LLM Serving and Scheduling Platform Hard Pro
- Bounded Thread-Pool Batch Executor Hard Pro
- Concurrent Chunked File Downloader with SHA-256 Verification Medium Pro