Bank app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-227stacks
A bank app has a calculator on its loan page. People type an expression such as 120 + 30 * 4 / 5 - 7 and read the result.
The calculator works with whole numbers and the four operations +, -, * and /. It follows the usual rules: * and / come before + and -, and operations of the same level go from left to right.
Division drops the fraction, toward zero. Spaces may appear anywhere between the parts. An expression can have up to 100,000 characters.
Write calculate(expression).
expression is a valid expression made of whole numbers that are 0 or more, the operators +, -, * and /, and spaces. There are no brackets, and no sign in front of a number.Input: expression = "12 + 3 * 4 - 8 / 3"
Output: 22Keep a stack of the terms of the sum. A + or - starts a new term, and * or / changes the newest one. At the end, add the terms up.
| Number read | Operator before it | What happens | Terms after |
|---|---|---|---|
| 12 | + |
+: a new term |
12 |
| 3 | + |
+: a new term |
12, 3 |
| 4 | * |
*: multiply the newest term |
12, 12 |
| 8 | - |
-: a new term, negative |
12, 12, -8 |
| 3 | / |
/: divide the newest term by 3, toward zero |
12, 12, -2 |
The terms are 12, 12 and -2, and their sum is 22. The term -8 divided by 3 is -2 and not -3, because division drops the fraction toward zero.
Input: expression = " 14 - 3 * 2 "
Output: 8Spaces are skipped. The product 3 * 2 comes first, so the value is 14 - 6 = 8.
Input: expression = "7"
Output: 7One number, and no operator: the value is 7.
1 ≤ length of expression ≤ 10^5A plan that rescans for the next * or / before every operation costs about n^2 / 10 steps when a long run of additions comes first. That is 10^9 steps for 100,000 characters, which is too slow.
So the work must be close to n steps in all. Each character should be read once, and each operator applied as soon as its right number is known.