InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Stack

Basic Calculator

hard Original ↗ 00:00

Problem

Evaluate an arithmetic expression given as a string s and return its value as an integer.

The expression may contain:

  • non-negative integer literals (possibly multi-digit),
  • binary + and -,
  • unary - (and unary +), e.g. "-2+1" or "-(3+4)",
  • parentheses ( ),
  • spaces, which are meaningless.

There is no multiplication or division, the expression is always valid, and no intermediate value overflows a 64-bit integer. You may not use eval() or any built-in expression evaluator.

Examples

Example 1

Input: s = "1 + 1" Output: 2 Explanation: spaces are ignored; simple addition.

Example 2

Input: s = " 2-1 + 2 " Output: 3 Explanation: left-to-right evaluation, 2 - 1 = 1, then 1 + 2 = 3.

Example 3

Input: s = "-(5 - (1 + 2))" Output: -2 Explanation: the inner sum is 3, 5 - 3 = 2, and the leading unary minus negates it.

Constraints

  • 1 <= s.length <= 3 * 10^5
  • s consists of digits, +, -, (, ), and ' '.
  • The length bound demands a single O(n) pass — re-evaluating innermost parentheses repeatedly is too slow.

Think about it first

Hint 1 With only + and −, every term is just added — a `-` is the same as adding the next value multiplied by −1. Can you carry a "current sign" instead of doing subtraction?
Hint 2 The only real difficulty is parentheses: `-(...)` must negate everything inside. What do you need to remember when you enter a `(` so you can resume correctly at the matching `)`?
Hint 3 Keep a running `result` and a `sign` (+1/−1). On `(`, push both onto a stack and reset them; on `)`, finish the inner result, pop, and combine: `result = popped_result + popped_sign * inner`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug