Single-Pass S-Expression Parser
Updated
Problem statement
Complete parseSExpression: given one simplified S-expression text, return it in the clean format below, or the position of its first error. Read text once from left to right, keeping its atoms and nested lists. Do not use split or break the whole input into tokens first.
The grammar is:
- An atom is a nonempty run of ASCII letters, digits, or
_ + - * /. - A list is
(, then zero or more expressions, then). - ASCII spaces, tabs, carriage returns and newlines may separate expressions and surround the one root expression. Parentheses also separate atoms, so whitespace next to a parenthesis is optional.
In the output, keep every atom exactly as written, drop all whitespace from the input, and put exactly one space between neighboring list elements. An empty list becomes ().
Stop at the first syntax error and return ERROR@i, where i is the zero-based index in the input where the error is found. Errors include an unsupported character, an unmatched closing parenthesis, an extra root expression, or input that ends too early. If the expression is still incomplete when the input ends, i is text.length. An empty or whitespace-only input also reports that end position.
Function
parseSExpression(text: String) → StringExamples
Example 1
text = " (* 2 (+ 3 4))\n"return = "(* 2 (+ 3 4))"The leading spaces and the trailing newline are dropped, and the nested lists stay as written.
Example 2
text = "(a @ b)"return = "ERROR@3"@ is not allowed anywhere in the grammar, and it sits at index 3, so parsing stops there.
Constraints
0 <= text.length <= 10000.- Every input character is printable ASCII, a tab, a carriage return or a newline. Printable characters outside the grammar may appear and must produce an error.
- Parenthesis nesting in any valid prefix is at most
200. - The input may be malformed.
More Baseten interview questions
Similar questions at other companies
- Calculator with ParenthesesGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Evaluate an Arithmetic Expression with DivisionMotive · ONSITE INTERVIEWMotive interview questions
- Remove Parentheses from a Plus-Minus ExpressionOracle · PHONE SCREENOracle interview questions
- Decode StringCompass International Holdings · PHONE SCREENCompass International Holdings interview questions
- Flatten JSON With Array IndicesAdobe · PHONE SCREENAdobe interview questions
- Decode StringSambaNova Systems · PHONE SCREENSambaNova Systems interview questions
- Plus and Minus CalculatorIndeed · PHONE SCREENIndeed interview questions
- Arithmetic Expression EvaluatorMicrosoft · PHONE SCREENMicrosoft interview questions
- Most Frequent Call Path From Function Trace LogsRoblox · PHONE SCREEN · ONSITE INTERVIEWRoblox interview questions
- Flatten a Mixed JSON ListNike, Inc. · ONSITE INTERVIEWNike, Inc. interview questions