Skip to main content

227. Basic Calculator II

mediumAsked at Meta

Evaluate a string expression with +, -, *, / and non-negative integers. Meta asks this to test whether you reach for the stack-based delayed-add pattern that handles precedence without recursion or explicit token parsing.

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

Source citations

Public interview reports confirming this problem appears in Meta loops.

  • Glassdoor (2026-Q1)Meta E4 onsite reports cite this as a recurring calculator problem.
  • Blind (2025-09)Recurring Meta interview problem.

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].

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].

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

Approaches

1. Stack with delayed-add (optimal)

Track the previous operator. On +/-, push the current number (signed) to the stack. On *://, pop the top, apply the op, push the result.

Time
O(n)
Space
O(n)
function calculate(s) {
  const stack = [];
  let num = 0;
  let op = '+';
  for (let i = 0; i < s.length; i++) {
    const c = s[i];
    if (c >= '0' && c <= '9') num = num * 10 + Number(c);
    if ((!(c >= '0' && c <= '9') && c !== ' ') || i === s.length - 1) {
      if (op === '+') stack.push(num);
      else if (op === '-') stack.push(-num);
      else if (op === '*') stack.push(stack.pop() * num);
      else if (op === '/') {
        const prev = stack.pop();
        stack.push(prev >= 0 ? Math.floor(prev / num) : -Math.floor(-prev / num));
      }
      op = c;
      num = 0;
    }
  }
  return stack.reduce((a, b) => a + b, 0);
}

Tradeoff: Single linear pass. Stack holds pending additions; multiplications and divisions modify the top in place. At the end, sum the stack. Handles precedence elegantly without explicit token parsing.

2. Stack-free with running state (alternative optimal)

Track lastNum + result. On +/-, add lastNum to result, set lastNum to current. On */, apply to lastNum directly.

Time
O(n)
Space
O(1)
function calculateNoStack(s) {
  let result = 0;
  let lastNum = 0;
  let curr = 0;
  let op = '+';
  for (let i = 0; i < s.length; i++) {
    const c = s[i];
    if (c >= '0' && c <= '9') curr = curr * 10 + Number(c);
    if ((!(c >= '0' && c <= '9') && c !== ' ') || i === s.length - 1) {
      if (op === '+') { result += lastNum; lastNum = curr; }
      else if (op === '-') { result += lastNum; lastNum = -curr; }
      else if (op === '*') lastNum *= curr;
      else if (op === '/') lastNum = lastNum >= 0 ? Math.floor(lastNum / curr) : -Math.floor(-lastNum / curr);
      op = c;
      curr = 0;
    }
  }
  return result + lastNum;
}

Tradeoff: O(1) extra space — beats the stack version on memory. Tricky to get right under pressure because lastNum has subtle invariants.

Meta-specific tips

Meta interviewers grade this on whether you can handle precedence without recursion. State out loud: 'For + and -, I push and accumulate; for * and /, I apply to the most recent number. The stack defers the + sum until I know there's no higher-precedence operation immediately after.' Walking through the delayed-add intuition before coding earns the bar.

Common mistakes

  • Forgetting the special-case for the last number (loop bound check).
  • Integer division towards zero is NOT the same as Math.floor for negatives (-7 / 2 should be -3, not -4).
  • Skipping spaces with a continue that fails to update i — keep the conditional simple.

Follow-up questions

An interviewer at Meta may pivot to one of these next:

  • Basic Calculator (LC 224): add parentheses (use a stack for nesting).
  • Basic Calculator III (LC 772): combine I + II.
  • Reverse Polish Notation evaluation.

Solve it now

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

Output

Press Run or Cmd+Enter to execute

FAQ

Why a stack?

The stack defers + and - until you know whether the next operation is * or / (higher precedence). Once you see +/-, you can safely commit the current number to the running sum.

Why is integer division tricky?

Math.floor rounds toward -infinity for negatives; the problem says truncate toward zero. So Math.floor(-7 / 2) = -4 is wrong; the answer is -3. Use the sign-aware formula or Math.trunc.

Practice these live with InterviewChamp.AI

Drill Basic Calculator II and other Meta interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →