AlgoInsight

DSA problem

Basic Calculator II

MediumStacksPattern: Stackstop300AmazonMicrosoftGoogleMetaBloomberg

Given a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-2^31, 2^31 - 1].

s consists of integers and operators +, -, *, / separated by some number of spaces. Notice the important distinction from "Basic Calculator I": this problem has * and / but no parentheses. The challenge is correctly handling operator precedence — multiplication and division must be applied before addition and subtraction.

A clean recursive-descent parser would work, but a single-pass stack-based approach is simpler and faster. The trick is to remember the previous operator and the current number. As you scan the string and parse a complete number, you decide what to do with it based on the previous operator. If the previous operator was + or -, you push the number (with a sign for -) onto a stack; you don't sum it in yet, because a later * or / could attach to it. If the previous operator was * or /, you pop the top of the stack, apply the operator with the current number, and push the result back, so that the chain of *// is folded immediately.

After the scan, the stack contains numbers that should just be summed (since multiplication and division have all been resolved into the stack values). Returning the sum of the stack is the answer. This runs in O(n) time and O(n) space.

Examples

Example 1
Input: s = "3+2*2"
Output: 7
Explanation: 2*2 = 4, then 3+4 = 7.
Example 2
Input: s = " 3/2 "
Output: 1
Explanation: Integer division truncates toward zero.
Example 3
Input: s = " 3+5 / 2 "
Output: 5
Explanation: 5 / 2 = 2 (truncated), then 3 + 2 = 5.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stackstringmathparsing

Browse all DSA problems