Basic Calculator
Problem Statement
You are given a string s that holds an arithmetic expression with brackets. Return its value.
- The expression has non-negative integers,
+,-,(,)and spaces. There is no*or/. -can be used as a unary minus, like"-1"or"-(2 + 3)".+is never unary.- Two operators never appear next to each other (but
"1-(-2)"is fine, because there is a bracket in between). - You may not use a built-in function like
eval().
A string s made of digits, + - ( ) and spaces. It is always a valid expression.
The integer value of the expression.
Left to right: 2 − 1 = 1, then 1 + 2 = 3.
The inner bracket (4+5+2) is 11, so the first group is 1 + 11 − 3 = 9. The second group is 14. 9 + 14 = 23.
- • 1 ≤ s.length ≤ 3 · 10^5
- • `s` contains only digits, `+ - ( )` and spaces, and is a valid expression
- • `+` is never unary; `-` may be unary
- • Every number and every running result fits in a 32-bit int
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Find an innermost (…), evaluate it flat, splice its value into the string, repeat
A function evaluates until ')'; on '(' it calls itself for the group
On '(' push (result, sign) and reset; on ')' result = saved + savedSign · result
The first ) in the string and the last ( before it form an innermost bracket: nothing inside it has brackets. Evaluate that flat + - expression, replace the whole ( … ) with the resulting number, and repeat. When no brackets are left, evaluate the flat string.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Stack translate into production architectures and low-level memory mechanics.