Evaluate Calculator Expressions With Precedence, Parentheses, and Unary Minus

Last updated: November 29, 2026

Quick Overview

Implement an evaluator for integer arithmetic expressions typed into a search box calculator, supporting +, -, *, / (truncating toward zero), parentheses, unary plus and minus, and whitespace, and reporting syntax errors and division by zero.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Implement an evaluator for integer arithmetic expressions typed into a search box calculator, supporting +, -, *, / (truncating toward zero), parentheses, unary plus and minus, and whitespace, and reporting syntax errors and division by zero.

Typing an expression into Google Search returns a calculator answer, and this onsite question asks for the parsing core. The interviewer wants a principled approach (recursive descent from a grammar or shunting-yard), correct associativity, and unary minus handled without hacks.

What the Interviewer Expects
  • Writes the grammar with expression, term, and factor levels before coding
  • Separates tokenizing from parsing
  • Gets left associativity right for chains such as 1 - 2 - 3
  • Handles unary minus at any depth, such as -(2+3)*-2
  • Defines integer division semantics and reports errors precisely
Key Topics to Cover
Recursive Descent Parsing
Operator Precedence
Tokenization
Grammars
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Add exponentiation, which is right associative and binds tighter than unary minus in most calculators.
  • Add variables and function calls like max(a, 3).
  • Convert the parser to build an AST and constant-fold it; what does that buy you?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Integers, + - * /, parentheses, unary +/-, arbitrary whitespace.
  • * and / bind tighter than + and -; all binary operators are left associative.
  • Division truncates toward zero (`7 / ...
High-Level Design

Use the grammar:

  • expr := term (('+' | '-') term)*
  • term := factor (('*' | '/') factor)*
  • factor := ('+' | '-') factor | NUMBER | '(' expr ')'

Each rule becomes a function. The loops in `ex...


Submit Your Answer
Markdown supported