Basic Calculator II
Problem Statement
You are given a string s that holds a normal arithmetic expression, like "3+2*2". Return its value.
- The expression has non-negative integers and the operators
+,-,*,/. There are no brackets. *and/are done before+and-(normal school rules). Operators of the same strength go left to right.- Integer division truncates toward zero.
- There may be spaces anywhere between numbers and operators.
- 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.
2*2 is done first and gives 4, then 3 + 4 = 7.
3 / 2 = 1.5, which is cut to 1. The spaces are ignored.
5 / 2 is done first and gives 2, then 3 + 2 = 5.
- • 1 ≤ s.length ≤ 3 · 10^5
- • `s` contains only digits, `+ - * /` and spaces
- • `s` is a valid expression, and every number in it is in [0, 2^31 − 1]
- • The final answer fits in a 32-bit int
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Split into tokens, repeatedly collapse the first * or /, then add up
+ pushes n, − pushes −n, * and / change the top; answer = sum of stack
Keep the sum of finished terms and the latest term only
Do what you were taught in school. First split the string into numbers and operators. Then find the first * or /, compute it, and replace the three tokens by the result. Repeat until no * or / is left. Now only + and - remain, and those can be done left to right.
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.