Basic Calculator II
Problem
Evaluate an arithmetic expression given as a string s and return its integer value. The string contains non-negative integers, the operators +, -, *, /, and spaces. There are no parentheses. Operators follow the usual precedence (* and / before + and -, all left-associative), and integer division truncates toward zero. Do not use a built-in evaluator.
- The string has between 1 and 400,000 characters.
- The expression is valid and every intermediate value fits in a signed 32-bit integer.
- There is no division by zero.
Examples
s = "9+4*3"→21. Multiplication binds tighter, so it is9 + 12.s = " 17/5 "→3. Integer division truncates, and surrounding spaces are ignored.s = " 6+11 / 4 "→8.11 / 4is2, then6 + 2.s = "20-7/2"→17.7 / 2is3, so20 - 3.
Hints
+and-can be applied left to right, but*and/must combine with the number immediately before them. What do you need to remember about that number?- Think of the expression as a sum of signed terms, where each term is a chain of multiplications and divisions.
- Keep a stack of completed terms. When you see
*or/, pop the last term, combine it with the new number, and push it back. The answer is the sum of the stack.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Sign in with your email — no purchase — and this question opens in full, along with 12 others.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395