Vintage Calculator Tape

EasystackAlso known as Evaluate Reverse Polish Notation

An old office calculator has no = key and no brackets. You type a number, press Enter, type another, and then press an operator, which combines the two most recent numbers into one. To work out (2 + 1) × 3 you type 2, 1, +, 3, *.

The calculator prints every key on a paper tape. A shop found a box of old tapes, and wants to know the final number each one produced.

Your task

Write replayTape(tokens). tokens is the tape: each entry is either an integer written as a string (it may be negative, like "-5") or one of the operators "+", "-", "*", "/". An operator takes the two most recent numbers, a (older) and b (newer), and replaces them with a op b. Return the one number left at the end.

Division keeps only the whole part and rounds toward zero: 7 / 2 is 3 and -7 / 2 is -3.

replayTape(tokens: string[]) → int

Examples

Example 1
Input
tokens = ["2", "1", "+", "3", "*"]
Output
9
Why

2 and 1 are typed. + combines them into 3. Then 3 is typed, and * combines the two numbers waiting, 3 and 3, into 9.

Example 2
Input
tokens = ["4", "13", "5", "/", "+"]
Output
6
Why

4, 13 and 5 wait. / combines the two newest: 13 / 5 = 2.6, cut to 2. Now 4 and 2 wait, and + gives 6. The 4 waited the whole time for its partner.

Constraints

  • 1 ≤ tokens.length ≤ 10,000
  • Every tape is valid: an operator always has two numbers to use, and exactly one number is left at the end.
  • No division by zero. Every number, including intermediate results, is between -2,147,483,648 and 2,147,483,647.
Start with brute force

Scan the tape for the first spot where two numbers are followed by an operator, replace those three tokens with the result, and start the scan again. Repeat until one number is left.

Each scan finds one operation and the list shrinks by only two tokens, so a tape of 10,000 tokens needs about 5,000 scans of up to 10,000 tokens each, around 50 million steps. A stack does the whole tape in one pass.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code