Evaluate an Arithmetic Expression Without Parentheses or Eval
Last updated: November 29, 2026
Quick Overview
Given a string containing non-negative integers, the operators + - * /, and spaces, evaluate it with standard precedence. Integer division truncates toward zero, and you may not use eval or a library parser.
Meta
November 29, 20260
0
0 solved
Given a string containing non-negative integers, the operators + - * /, and spaces, evaluate it with standard precedence. Integer division truncates toward zero, and you may not use eval or a library parser.
Expression evaluation is a frequent Meta screen problem, the kind of logic that sits behind formula fields in internal tools or Ads Manager custom columns. Interviewers check that you handle precedence in one pass and parse multi-digit numbers and spaces cleanly.
What the Interviewer Expects
- Parses multi-digit numbers and skips spaces
- Handles * and / precedence in a single pass
- Truncates division toward zero, not floor
- Offers an O(1) space version without a full stack
- Tests mixed precedence like 14-3/2
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Add support for parentheses.
- Add unary minus, for example "-3*-2".
- How would you report a clear error for malformed input?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input is a valid expression with no parentheses and no unary operators. All intermediate results fit in 32-bit signed integers. Return an int. Target O(n) time....
High-Level Design
Keep last_op, initialized to '+'. Read a full number; when an operator or the end of the string arrives, apply last_op to that number. For + and -, commit the previous term to total and start a ...