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 Python int (such as -24 or 009 -> 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 as scale_by, -, -k, or *). Any token satisfying the integer rule is always classified as an int rather than a symbol str.
  • 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 Python list. 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 instance 85k or 4-1).
  • 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 at text[pos] and returns (parsed_atom, next_pos) where next_pos is 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 and O(len(text)) total memory without str.split(), regexes, or O(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

  1. 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 -24 or scale_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 kind and 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
    
  2. 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 index 3.

    Instead, advance one integer cursor pos monotonically from 0 to len(text). Every reader routine obeys the same contract:

    reader(text, pos)  -->  (parsed_value, next_pos)
    

    Here pos is where the routine starts reading inside text, and next_pos is 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 text is never copied or re-sliced ahead of time, pos is always the true global character index, and each character is visited only a constant number of times (O(n) total work).

  3. 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 of text. While stepping forward character by character, two checks catch atom failures at the exact offending offset:

    1. If ch is neither a delimiter nor in our ASCII atom alphabet (ATOM_CHARS), raise invalid_char at pos.
    2. 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 raise bad_number right at pos (so "85k" fails at 'k', index 2).

    Define explicit ASCII character strings (DIGITS, LETTERS) rather than calling Python's built-in str.isdigit() or str.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_integer tests whether text[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
    
  4. 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) advances pos across spaces, tabs, carriage returns, and newlines.
    • check_nothing_left(text, pos) skips trailing whitespace after the root expression and raises trailing_input if any character remains (catching "u v" at index 2).
    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 value
    

    Notice how " " behaves: skip_whitespace moves pos from 0 to 3 (len(text)), and parse_atom raises unexpected_end at index 3.

  5. Milestone 2: read a parenthesized list and isolate every error point

    Once read_list steps past an opening '(' recorded at open_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 append
    

    Every error class now has one dedicated check:

    • invalid_char and bad_number: inside read_atom
    • unclosed_list: at the top of read_list's loop when pos == len(text)
    • unexpected_close: inside read_expr when ')' sits where an expression must begin (e.g., parse(")"))
    • unexpected_end: inside read_expr when the whole string is empty or blank
    • trailing_input: inside check_nothing_left once the root expression completes (e.g., "(inc 1) 2" at 8, or "(u))" at 3)
    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)
    
  6. Milestone 3: unlock arbitrary nesting via mutual recursion

    Because read_expr delegates '(' to read_list, and read_list calls read_expr for 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_list consumes up through its closing ')' and returns pos + 1. The enclosing read_list resumes its while loop right at that updated pos.
    • Which '(' gets reported on premature end-of-input? Each active read_list call keeps its own open_index local variable. If the string ends mid-parse, execution is inside the deepest open read_list frame, which raises unclosed_list with its own open_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 default 1,000-frame limit comfortably supports ~500 nested levels (and the follow-up section replaces recursion with an explicit heap list for 100,000+ levels).

    Now parse(text) simply reads one root expression from index 0 and 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
    
  7. Trace Example 2 and Example 3 step by step

    First trace "(neg(y))" (indices 0..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)" (length 15, indices 0..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 at 10) closed cleanly at 14, leaving list #2 (opened at 5) as the innermost open list when the string runs out—so ParseError reports index 5.

  8. 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 = 0 sees '(', so read_list saves open_index = 0 and steps pos to 1.
  • pos = 1 calls read_atom, which scans "op", stops at the space at 3, and returns ("op", 3).
  • After skipping the space, pos = 4 sees '(', opening a nested read_list (open_index = 4) that reads "sub" (pos = 5..8) and integer 9 (pos = 9..10), hits ')' at pos = 10, and returns (["sub", 9], 11).
  • Finally, the outer read_list sees ')' at pos = 11, returns (["op", ["sub", 9]], 12), and check_nothing_left confirms index 12 is the end of the string.

Complexity

  • Time: O(n) for an input string of n characters. The integer cursor pos only advances forward from 0 to n, and each character is inspected a small constant number of times—once when advancing pos in skip_whitespace or read_atom, and at most twice more when slicing text[start:pos] and running is_integer / int(token). (Caveat: CPython's base-10 int() conversion is quadratic on multi-thousand-digit numbers, which is why Python 3.11+ caps int(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 uses O(n) memory in the input size, while mutual recursion (two functions calling each other) uses two Python call-stack frames (read_expr and read_list) per open parenthesis—O(d) stack space, supporting roughly 500 nested levels under Python's default 1,000-frame recursion limit.

Edge cases

  • Empty or whitespace-only input: "" fails with unexpected_end at index 0; " " advances past the spaces and fails with unexpected_end at index 3 (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 to 9 and "-0" parses to 0.
  • 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 with invalid_char because membership is checked against explicit ASCII sets rather than str.isdigit() (which returns True for '²') or int() (which accepts Unicode decimal digits).
  • Multiple errors in one string: "(u $ (v" halts right at '$' and raises invalid_char at index 3, never reaching the unclosed '(' at index 5.
  • Stray closing parentheses: ")" at the start of an expression raises unexpected_close at 0, whereas "(u))" completes the valid root list ["u"] at index 3 and raises trailing_input on the extra ')' at index 3.
  • Multi-thousand-digit integers: Python raises ValueError when int() exceeds 4,300 digits (sys.set_int_max_str_digits); in production code, catch ValueError around int(token) and wrap it in ParseError("bad_number", ..., start) so callers only ever handle ParseError.

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—taking O(n^2) time on deep inputs and resetting offsets to 0 inside every slice so reported error indices are wrong.
  • Scanning to the next delimiter first and validating the token afterward, causing "85k$" to blame index 3 ('$') even though the number broke at index 2 ('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_list and missing parse_atom("u v") or parse("y z").
  • Using str.isdigit() and str.isalpha(), silently accepting Unicode superscripts and accented letters as ASCII tokens.
  • Reporting len(text) as the error offset for unclosed_list instead of recording open_index at 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 stack where each open '(' pushes [items_list, open_index]. Every branch ('(', ')', atom, end-of-input, and trailing check) mirrors read_expr and read_list step for step, producing identical syntax trees and raising the exact same (kind, index) ParseError on every input while running in O(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) inside read_expr. read_string saves open_quote = pos, advances to pos + 1, and accumulates characters until an unescaped '"': spaces and parentheses inside quotes are copied literally (yet another reason split() parsers break on strings), while '\\' checks the next character to decode '\\"', '\\\\', '\\n', and '\\t'—raising bad_escape at the backslash for unknown escapes or unclosed_string at open_quote if pos reaches len(text). Also require a delimiter (whitespace, '(', ')', or end of input) immediately after the closing quote so "uv"w fails cleanly, and wrap either symbols (Symbol("y")) or strings in a distinct type so string "y" and symbol y stay 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: stack of open [items, open_index] frames, a token_buf string and token_start offset for any atom currently being scanned, a cumulative global_offset across chunks, and an incremental UTF-8 decoder (codecs.getincrementaldecoder("utf-8")()) in case a multi-byte sequence spans two packets. Calling feed(chunk) consumes characters and emits finished root expressions while holding any trailing unfinished atom in token_buf (since the next chunk could extend it); calling finish() at EOF flushes any buffered atom and raises unclosed_list or unexpected_end if 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 pos on the hot path so valid inputs pay zero extra cost, and convert index to 1-based (line, column) lazily only when constructing a ParseError. For instance, in "(u\n $)", '$' sits at index 5: counting "\n" before index 5 yields line = 1 + 1 = 2, and measuring from just past the last newline at index 2 yields column = 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 with bisect.

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 that yields 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_iterative directly as parse removes 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

Similar questions

More Baseten interview questions

All 8 Baseten questions →