Basic Calculator II Medium 0 attempts
LeetCode ↗

Basic Calculator II

Medium StringHash Table LeetCode

Given a string s representing a mathematical expression with non-negative integers and the operators +, -, *, /, return the result of evaluating it. Integer division should truncate toward zero. The expression contains no parentheses and is always valid.

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

Edge cases: Spaces anywhere in the string. Single number with no operators. Division that truncates (e.g., 14 / 3 = 4).

Sample Input
s = "3+2*2"
Sample Output
7
Constraints
  • 1 <= s.length <= 3 * 10^5
  • s contains digits, +, -, *, / and spaces
Test Cases
Case 1
Args: ["3+2*2"] Expected: 7

Approach: Stack with Operator Precedence

Scan left to right, building up each number. When you hit an operator (or the end), apply the previous operator: push for +/-, but pop-and-compute for *// so multiplication and division are handled before addition and subtraction. Sum the stack at the end.

function calculate(s) {
  const stack = [];
  let num = 0;
  let op = '+';

  for (let i = 0; i <= s.length; i++) {
    const ch = s[i];
    if (ch >= '0' && ch <= '9') {
      num = num * 10 + (ch - '0');
    } else if (ch === '+' || ch === '-' || ch === '*' || ch === '/' || i === s.length) {
      if (op === '+') stack.push(num);
      else if (op === '-') stack.push(-num);
      else if (op === '*') stack.push(stack.pop() * num);
      else if (op === '/') stack.push(Math.trunc(stack.pop() / num));
      op = ch;
      num = 0;
    }
  }
  return stack.reduce((a, b) => a + b, 0);
}

Time Complexity: O(n)

Space Complexity: O(n) for the stack

Saved in this browser only. Private to you.

JavaScript