Skip to main content

227. Basic Calculator II

medium

Evaluate a math string with +, -, *, / and non-negative integers — without parentheses, but with operator precedence. The textbook stack-based precedence handling.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

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]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

Constraints

  • 1 <= s.length <= 3 * 10^5
  • s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.
  • s represents a valid expression.
  • All the integers in the expression are non-negative integers in the range [0, 2^31 - 1].
  • The answer is guaranteed to fit in a 32-bit integer.

Examples

Example 1

Input
s = "3+2*2"
Output
7

Example 2

Input
s = " 3/2 "
Output
1

Example 3

Input
s = " 3+5 / 2 "
Output
5

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Operator precedence is the wrinkle: * and / bind tighter than + and -.

Hint 2

Walk the string with a stack of integer terms. Maintain a 'pending operator' that starts at '+' (the implicit leading sign).

Hint 3

When you finish parsing a number n, look at the pending operator: '+' push n; '-' push -n; '*' push stack.pop * n; '/' push trunc(stack.pop / n). Then update the pending operator for the next round.

Hint 4

After the loop, sum the stack. The * and / consumed their left operand on the spot; only the additive terms remain.

Solution approach

Reveal approach

Stack-based two-pass-as-one. Initialize an empty stack and a pending_op = '+'. Walk the string: parse a number, then on seeing an operator (or hitting the end of the string), apply pending_op: '+' push num; '-' push -num; '*' top = stack.pop, push top * num; '/' top = stack.pop, push int(top / num) using truncation-toward-zero. Then update pending_op to the new operator. After the loop, sum the stack and return. The trick is treating each + or - as 'commit the previous term, queue the new sign', while * and / fold the new number into the most-recent term on the stack. O(n) time, O(n) space.

Complexity

Time
O(n)
Space
O(n)

Related patterns

  • stack
  • math
  • string-scan

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Google
  • Microsoft
  • Apple

Practice these live with InterviewChamp.AI

Drill Basic Calculator II and Math problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →