Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Stack

The stack as an evaluator

Lesson · 10 min read · Stack · The stack as an evaluator

How a single stack works out an arithmetic expression in one pass, starting with postfix and the order of the two pops before moving on to brackets and precedence.

Numbers wait until an operator needs them

In postfix notation (people also call it reverse Polish) every operator is written straight after the two values it works on, so 2 1 + 3 * means (2 + 1) × 3. I'd always start with postfix when I'm teaching this, because the expression has already decided the order of the arithmetic for you and there aren't any brackets or precedence rules to think about yet.

You read the tokens from left to right and keep pushing numbers onto the stack until an operator turns up that needs them. The operator pops the top two values, combines them and pushes the result back, and when you get to the end there ought to be exactly one value left over, which is your answer. If there are two values left at the end (or an operator finds fewer than two values underneath it) then I'd say the expression wasn't valid to begin with, and in an interview it's worth asking what they'd like you to return in that case.

Postfix evaluation

evaluate(tokens)

  1. Start with an empty stack and read the tokens one at a time, beginning from the left.
  2. If the token's a number, you push it and leave it there until something needs it.
  3. If it's an operator, you pop b first and then a, and push a op b back onto the stack.
  4. When you've read every token, whatever single value is left on the stack is your answer.
TimeO(n)
SpaceO(n)

Every token's pushed at most once and popped at most once, and if all the numbers come first the stack ends up holding roughly half of the tokens.

Here's 4 13 5 / + 3 -, which comes out as 4 + 2 − 3 = 3 (the division 13 / 5 truncates to 2).

  1. Step 1 / 8
    tokens
    40i13152/3+435-6
    stack
    40

    4 is a number, so I'd push it and leave it there until some operator needs it.

  2. Step 2 / 8
    tokens
    40131i52/3+435-6
    stack
    40131

    13 goes on top as well, because nothing has asked for it yet.

  3. Step 3 / 8
    tokens
    4013152i/3+435-6
    stack
    4013152

    Another number, 5, and that's pushed on top of whatever's waiting.

  4. Step 4 / 8
    tokens
    4013152/3i+435-6
    stack
    4021
    13 / 52

    '/' needs two values, so it pops 5 first (that's the right-hand one) and then 13, works out 13 / 5 = 2 and pushes the result back.

  5. Step 5 / 8
    tokens
    4013152/3+4i35-6
    stack
    60
    4 + 26

    Then '+' takes 2 and 4 off the top and puts back 6, since 4 + 2 = 6.

  6. Step 6 / 8
    tokens
    4013152/3+435i-6
    stack
    6031

    3 is a number, so I'd push it and leave it there until some operator needs it.

  7. Step 7 / 8
    tokens
    4013152/3+435-6i
    stack
    30
    6 - 33

    Then '-' takes 3 and 6 off the top and puts back 3, since 6 - 3 = 3.

  8. Step 8 / 8
    stack
    30
    answer3

    Every token's been used and exactly one value is left on the stack, so the answer is 3.

Which value comes off first

The mistake I see most often with students is popping the two values in the wrong order, and I think it's because the stack hands them back to you reversed. Whatever's sitting on top is the right-hand operand, so with 13 followed by 5 and a divide you'd pop the 5 first and the 13 second, and then work out 13 divided by 5. If you swap them by accident, addition and multiplication still come out right (which is probably why the bug survives the first couple of tests you try), although subtraction and division go wrong immediately.

Division has a second trap as well, because most versions of this problem want integer division that truncates towards zero. That means minus 7 divided by 2 should give you −3, whereas Python's floor division rounds downwards and would hand you −4 instead. In Python I'd write int(a / b) and in JavaScript Math.trunc(a / b), and in C++ or Java you probably won't need to do anything at all, since dividing two integers there already truncates towards zero.

Before I submit I always try "7 2 -", which should give 5, and "-7 2 /", which should give −3. Getting −5 or −4 means you've fallen into one of those two traps.

Brackets, by saving what you were doing

An ordinary expression with brackets looks a lot harder at first sight, although when the only operators are plus and minus a bracket can only keep or flip the sign of everything inside it. What I'd usually do is keep a running total along with the sign that applies to whichever number comes next. When an opening bracket arrives you push the current total and the sign in front of the bracket, then start again from 0 inside it, and when the bracket closes you pop those two values and fold the bracket's result back into the outer total.

However, you might recognise this from the bracket matching earlier in the chapter, because the bracket that closes is always the most recent one opened, and the stack is essentially remembering what you were in the middle of calculating when you went inside.

The case I'd want you to test before submitting is a minus sitting directly in front of a bracket with nothing before it, as in -(2 + 3) + 10. Because the running total starts at 0, the opening bracket saves 0 together with the minus, the bracket itself comes to 5, and when it closes you get 0 − 5 = −5, so adding the 10 afterwards gives 5 (which is correct). A solution that treats the first minus as part of the number usually breaks on it, and I've seen people spend ten minutes looking for the problem in the wrong place.

TimeO(n)
SpaceO(n)

You're reading every character once, and the stack holds one saved pair for each bracket that's still open, so I'd expect its size to depend on how deeply the brackets are nested rather than on how long the expression is.

In the trace below I've used 5 - (2 - (1 + 4)), where the innermost bracket comes to 5, the middle bracket therefore comes to 2 minus 5 (which is −3), and the whole expression works out as 5 minus −3, which is 8.

  1. Step 1 / 9
    saved
    total5sign+

    The first number you read is 5, and since there's no minus in front of it the running total starts off at 5.

  2. Step 2 / 9
    saved
    5, −0
    total0sign+

    When you reach an opening bracket you save the total so far (5) together with the minus that's written in front of the bracket, and then you start counting again from 0.

  3. Step 3 / 9
    saved
    5, −0
    total2sign+

    Inside the bracket you're counting from 0 again, so 2 on its own makes the total 2 (the outer total is safely on the stack).

  4. Step 4 / 9
    saved
    5, −02, −1
    total0sign+

    Another bracket opens, so you push 2 and its minus on top of what you saved earlier and the count restarts at 0.

  5. Step 5 / 9
    saved
    5, −02, −1
    total1sign+

    This bracket starts from 0 as well, so once you've read 1 its total is 1 while the saved pairs wait underneath.

  6. Step 6 / 9
    saved
    5, −02, −1
    total5sign+

    You add 4 because there's a plus in front of it, which brings the total up to 5.

  7. Step 7 / 9
    saved
    5, −0
    total-3sign+

    This bracket closes having come to 5, so you pop the saved 2 with its minus and fold the bracket back in, which gives 2 − 5 = -3.

  8. Step 8 / 9
    saved
    total8sign+

    This bracket closes having come to -3, so you pop the saved 5 with its minus and fold the bracket back in, which gives 5 − (-3) = 8.

  9. Step 9 / 9
    saved
    answer8

    That's the end of the string, and since there's nothing left saved on the stack you can return the total, which is 8.

Times and divide without a second stack

Once the expression has all four operators (but still no brackets) I'd probably handle precedence with a single stack of signed numbers, and as you read each number you remember which operator was written just before it. A number that follows a plus is pushed exactly as it is, and one that follows a minus is pushed as its negative. However, multiplication and division are the interesting operations, because they usually can't wait: you pop the value on top, combine it with the new number straight away and push what you get back onto the stack. By the time you reach the end, I think you'll find that adding up everything remaining on the stack gives you the answer.

Let's try it on 3 + 2 × 2 − 8 ÷ 4. To begin with the stack holds only 3, then it holds 3 and 2, and when the second 2 arrives it multiplies the value on top so the stack becomes 3 and 4. The minus pushes −8, the division immediately turns that into −2, and adding up 3, 4 and −2 gives 5. You'll probably notice that the multiplications and divisions are performed as soon as their right-hand number turns up (which is really all that precedence means here), whereas the additions sit there until the very end. If the question also includes brackets, I'd generally wrap the bracket handling from the previous section around this loop, and that's usually enough.

Problems in this module