One moving cursor turns a messy string into a problem you can actually explain.
Give me add(2,3) and I can practically hear the temptation to split the string and move on. Find the comma, grab two numbers, return five, and enjoy a very brief feeling of competence.
Then somebody hands over add(5,mul(2,pow(5,2))).
Now there are three commas, several closing brackets and a function sitting where a number was supposed to be. The arithmetic is still friendly. Deciding which pieces belong together is where the interview starts getting interesting.
I like this question because you do not need a compiler course to solve it. You need one precise promise about what a helper function consumes and where it stops.
Let’s build that promise before writing the code, because it is the part worth remembering when the function names change.
Give the outer function exactly two arguments
Our calculator accepts five names, add, sub, mul, div and pow. Every call takes exactly two arguments. An argument can be an integer, including a negative one, or another complete call. Spaces may appear between tokens.
For the outer add, the arguments are 5 and the whole expression mul(2,pow(5,2)). Its inner commas belong to inner calls.
That is why a plain comma split falls apart. It sees punctuation without understanding which level owns it. You could track bracket depth while finding the outer separator, but repeatedly slicing and rescanning nested substrings can do unnecessary work.
Instead, let one cursor travel forward through the original string. A helper will consume one expression and return its value. Whoever called the helper handles the punctuation that comes next.
Before continuing, try drawing those two outer arguments yourself using the Google-tagged nested arithmetic question. Then mark where the cursor should land after evaluating the left argument. The listing is a reported interview exercise, not an official Google question bank.
Make the helper’s promise almost boring
Call the helper parse(). Starting at the current cursor, it skips whitespace, reads one complete expression, returns the result and leaves the cursor immediately after that expression.
It does not swallow the caller’s comma just to be helpful. Honestly, a helpful parser that eats somebody else’s punctuation is how this gets confusing.
If the next token is an integer, consume its optional minus sign and digits. If it is a function name, consume the opening bracket, parse the left expression, consume the comma, parse the right expression and consume the closing bracket. Then apply the function to those two values in that order.
Notice that the same helper handles both arguments. You never need a separate special case for a function inside a function inside another function. That is the lovely little payoff of describing the input recursively.
Walk one example all the way back up
In add(5,mul(2,pow(5,2))), the innermost pow returns 25. The waiting mul now has 2 and 25, so it returns 50. Finally, add has 5 and 50, which gives us 55.
Every pending call needs only its function name and the argument values it has already received. We do not have to build a separate tree in memory to evaluate this input. The picture explains the structure; the call stack remembers it while the cursor moves forward.
Operand order still matters. Swapping the arguments in addition might hide a mistake, while sub(10,3) immediately exposes it. Keep left and right visibly separate in the code.
Agree on arithmetic before Python agrees for you
The source question leaves some arithmetic rules unspecified, so these are our practice choices. Division truncates toward zero, negative exponents are rejected, and pow(0,0) returns 1. Integers have Python’s arbitrary precision, subject to available resources. Decimal literals are outside this version.
That makes div(-7,2) equal to -3. Python’s // rounds down instead, producing -4 for -7 // 2, as its arithmetic documentation explains. Divide the absolute values using integers, then restore the sign. Going through int(a / b) introduces floating-point conversion that we do not need.
We will also reject invalid syntax, unknown names, division by zero and trailing input. A successful parse of add(1,2) should not quietly bless add(1,2)junk.
Write the parser around that promise
This implementation uses one shared cursor and a small nesting limit for the exercise. It evaluates only the five operations we named; it does not execute the string as Python code.
def evaluate(text):
i = 0
def skip_spaces():
nonlocal i
while i < len(text) and text[i].isspace():
i += 1
def consume(symbol):
nonlocal i
skip_spaces()
if i == len(text) or text[i] != symbol:
raise ValueError(f'Expected {symbol} at {i}')
i += 1
def apply(name, a, b):
if name == 'add':
return a + b
if name == 'sub':
return a - b
if name == 'mul':
return a * b
if name == 'div':
if b == 0:
raise ZeroDivisionError('Division by zero')
q = abs(a) // abs(b)
return -q if (a < 0) != (b < 0) else q
if b < 0:
raise ValueError('Negative exponent')
return a ** b
def parse(depth=0):
nonlocal i
if depth > 100:
raise ValueError('Nesting limit exceeded')
skip_spaces()
if i == len(text):
raise ValueError('Missing expression')
start = i
if text[i] == '-' or '0' <= text[i] <= '9':
if text[i] == '-':
i += 1
digits = i
while i < len(text) and '0' <= text[i] <= '9':
i += 1
if i == digits:
raise ValueError('Missing digits')
return int(text[start:i])
while i < len(text) and 'a' <= text[i] <= 'z':
i += 1
name = text[start:i]
if name not in {'add', 'sub', 'mul', 'div', 'pow'}:
raise ValueError('Unknown function')
consume('(')
left = parse(depth + 1)
consume(',')
right = parse(depth + 1)
consume(')')
return apply(name, left, right)
result = parse()
skip_spaces()
if i != len(text):
raise ValueError('Unexpected trailing input')
return result
Read the last four lines carefully. Parsing one expression and consuming the entire input are different checks. That final check is what catches the extra junk after an otherwise valid call.
The depth guard is a deliberate practice limit, not a complete resource policy. Even a shallow expression can request an enormous exponentiation. A public calculator would also need limits on input length, numeric size and computation, and very deep supported inputs would need an explicit stack instead of relying on Python recursion.
Pick tests that cannot accidentally flatter your code
A few successful additions will make an impressive-looking green test report without checking the awkward decisions. Choose cases that expose the exact rule you could have misunderstood.
Add a whitespace-heavy expression and a plain negative integer too. This grammar allows -12, but it does not treat - 12 as one integer token. Spaces between tokens and spaces inside a token are different promises.
I checked the implementation against fixed examples, invalid inputs, its nesting guard and 500 generated expression trees with independently calculated expected values. Those checks cover the stated exercise; they are not a claim that arbitrary hostile input is safe to evaluate without resource limits.
For your own practice, predict each expected result before running anything. If an explanation takes longer than the code, that is a useful place to spend the next ten minutes.
Explain the cost without hiding the big numbers
Let n be the number of characters and d the nesting depth. The cursor-based syntax scan is O(n), and recursive frames take O(d) space. Each character is examined only a bounded number of times; we are not searching the same nested substring again and again.
That is the parsing cost, though. Integer conversion and arithmetic also cost time, and arbitrary-precision intermediate values occupy memory. pow(2,1000000) makes it pretty obvious why evaluating the whole expression is not automatically O(n) under a realistic arithmetic model.
In an interview, state the simplified fixed-size-number analysis if requested, then name the assumption. That small distinction makes your complexity answer much easier to defend.
Take the promise into the next problem
Try adding one operation after this version works. If the grammar stays the same, most of the parser should stay the same too. If you allow a variable number of arguments, explain which part of the grammar changes before reaching for another conditional.
The useful thing to keep from this exercise is not a memorized calculator. It is a helper that consumes exactly what it promised and leaves the rest for its caller.
When a string looks intimidating, find the smallest complete piece inside it. Sometimes the clean solution begins with being very particular about who gets to eat the next comma.
~ Emily





Top comments (0)