Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Move from brute-force thinking to an efficient approach using math strategy.
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = "3+2*2" Output: 7
Example 2:
Input: s = " 3/2 " Output: 1
Example 3:
Input: s = " 3+5 / 2 " Output: 5
Constraints:
1 <= s.length <= 3 * 105s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.s represents a valid expression.[0, 231 - 1].Problem summary: Given a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math · Stack
"3+2*2"
" 3/2 "
" 3+5 / 2 "
basic-calculator)expression-add-operators)basic-calculator-iii)evaluate-valid-expressions)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #227: Basic Calculator II
class Solution {
public int calculate(String s) {
Deque<Integer> stk = new ArrayDeque<>();
char sign = '+';
int v = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
v = v * 10 + (c - '0');
}
if (i == s.length() - 1 || c == '+' || c == '-' || c == '*' || c == '/') {
if (sign == '+') {
stk.push(v);
} else if (sign == '-') {
stk.push(-v);
} else if (sign == '*') {
stk.push(stk.pop() * v);
} else {
stk.push(stk.pop() / v);
}
sign = c;
v = 0;
}
}
int ans = 0;
while (!stk.isEmpty()) {
ans += stk.pop();
}
return ans;
}
}
// Accepted solution for LeetCode #227: Basic Calculator II
func calculate(s string) int {
sign := '+'
stk := []int{}
v := 0
for i, c := range s {
digit := '0' <= c && c <= '9'
if digit {
v = v*10 + int(c-'0')
}
if i == len(s)-1 || !digit && c != ' ' {
switch sign {
case '+':
stk = append(stk, v)
case '-':
stk = append(stk, -v)
case '*':
stk[len(stk)-1] *= v
case '/':
stk[len(stk)-1] /= v
}
sign = c
v = 0
}
}
ans := 0
for _, v := range stk {
ans += v
}
return ans
}
# Accepted solution for LeetCode #227: Basic Calculator II
class Solution:
def calculate(self, s: str) -> int:
v, n = 0, len(s)
sign = '+'
stk = []
for i, c in enumerate(s):
if c.isdigit():
v = v * 10 + int(c)
if i == n - 1 or c in '+-*/':
match sign:
case '+':
stk.append(v)
case '-':
stk.append(-v)
case '*':
stk.append(stk.pop() * v)
case '/':
stk.append(int(stk.pop() / v))
sign = c
v = 0
return sum(stk)
// Accepted solution for LeetCode #227: Basic Calculator II
struct Solution;
use std::iter::Peekable;
use std::slice::Iter;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Tok {
Num(i32),
Op(char),
}
use Tok::*;
impl Tok {
fn is_expr_op(self) -> bool {
matches!(self, Op('+') | Op('-'))
}
fn is_factor_op(self) -> bool {
matches!(self, Op('*') | Op('/'))
}
fn val(self) -> Option<i32> {
match self {
Num(x) => Some(x),
_ => None,
}
}
fn eval(self, lhs: i32, rhs: i32) -> Option<i32> {
match self {
Op('+') => Some(lhs + rhs),
Op('-') => Some(lhs - rhs),
Op('*') => Some(lhs * rhs),
Op('/') => {
if rhs != 0 {
Some(lhs / rhs)
} else {
None
}
}
_ => None,
}
}
}
impl Solution {
fn calculate(s: String) -> i32 {
let tokens = Self::tokens(&s);
let mut it = tokens.iter().peekable();
if let Some(val) = Self::parse_expr(&mut it) {
val
} else {
0
}
}
fn parse_expr(it: &mut Peekable<Iter<Tok>>) -> Option<i32> {
let mut lhs = Self::parse_factor(it)?;
while let Some(&tok) = it.peek() {
if tok.is_expr_op() {
let op = *it.next().unwrap();
let rhs = Self::parse_factor(it)?;
lhs = op.eval(lhs, rhs)?;
} else {
break;
}
}
Some(lhs)
}
fn parse_factor(it: &mut Peekable<Iter<Tok>>) -> Option<i32> {
let mut lhs = Self::parse_num(it)?;
while let Some(&tok) = it.peek() {
if tok.is_factor_op() {
let op = *it.next().unwrap();
let rhs = Self::parse_num(it)?;
lhs = op.eval(lhs, rhs)?;
} else {
break;
}
}
Some(lhs)
}
fn parse_num(it: &mut Peekable<Iter<Tok>>) -> Option<i32> {
match it.next() {
Some(Tok::Num(x)) => Some(*x),
_ => None,
}
}
fn tokens(s: &str) -> Vec<Tok> {
let mut v: Vec<Tok> = vec![];
let mut it = s.chars().peekable();
while let Some(c) = it.next() {
match c {
'0'..='9' => {
let mut x: i32 = (c as u8 - b'0') as i32;
while let Some(c) = it.peek() {
if c.is_numeric() {
x *= 10;
x += (it.next().unwrap() as u8 - b'0') as i32;
} else {
break;
}
}
v.push(Tok::Num(x));
}
'+' | '-' | '*' | '/' => {
v.push(Tok::Op(c));
}
_ => {}
}
}
v
}
}
#[test]
fn test() {
let s = "3+2*2".to_string();
assert_eq!(Solution::calculate(s), 7);
let s = "0-0".to_string();
assert_eq!(Solution::calculate(s), 0);
let s = "0-2147483647".to_string();
assert_eq!(Solution::calculate(s), -2_147_483_647);
}
// Accepted solution for LeetCode #227: Basic Calculator II
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #227: Basic Calculator II
// class Solution {
// public int calculate(String s) {
// Deque<Integer> stk = new ArrayDeque<>();
// char sign = '+';
// int v = 0;
// for (int i = 0; i < s.length(); ++i) {
// char c = s.charAt(i);
// if (Character.isDigit(c)) {
// v = v * 10 + (c - '0');
// }
// if (i == s.length() - 1 || c == '+' || c == '-' || c == '*' || c == '/') {
// if (sign == '+') {
// stk.push(v);
// } else if (sign == '-') {
// stk.push(-v);
// } else if (sign == '*') {
// stk.push(stk.pop() * v);
// } else {
// stk.push(stk.pop() / v);
// }
// sign = c;
// v = 0;
// }
// }
// int ans = 0;
// while (!stk.isEmpty()) {
// ans += stk.pop();
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.