InterviewPrepKit

Home / Coding / Stack

Basic Calculator

hard Original β†—
Solving tips
  • Key insight: with only + and -, there is no precedence, just carry a running result and a current sign (+1/-1); subtraction is adding sign*-1.
  • On '(' push (result, sign) and reset both; on ')' flush the inner number then combine result = prev_result + prev_sign * inner.
  • Target O(n) time and O(n) space; prefer the explicit iterative stack over recursion since deep nesting can exceed the recursion limit at n up to 3e5.
  • Common pitfalls: accumulate multi-digit numbers with num=num*10+digit, do the final result+sign*num flush after the loop, and push the sign (not just result) at '(' so -(1+2) negates correctly.

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`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.