‹ DS&A interview · Socratic
DSA · Stack · #37

Basic Calculator

Module 45 · difficulty 4/5·30:00starts on first keystroke

Given a string `s` representing a valid arithmetic expression, evaluate it and return its integer result. The expression contains only non-negative integers, the operators `+` and `-`, the parentheses `(` and `)`, and spaces. Unary minus is allowed (e.g. `-(2 + 3)` or `(-1)`). Implement `function calculate(s)` returning a number. You may NOT use `eval` or any equivalent built-in expression evaluator.

Examples
  • s = "1 + 1" 2
  • s = " 2-1 + 2 " 3
  • s = "(1+(4+5+2)-3)+(6+8)" 23Nested parentheses resolve to 14 + 9.
Constraints
  • · 1 <= s.length <= 3 * 10^5
  • · s consists of digits, '+', '-', '(', ')', and ' '.
  • · s represents a valid expression.
  • · All intermediate values fit in a signed 32-bit integer.
  • · There will be no two consecutive operators; a '-' before a number/'(' is treated as unary.
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.