Evaluate a Promotion Pricing Formula With Parentheses and Precedence
Last updated: November 29, 2026
Quick Overview
Pricing rules are stored as integer expressions like `(price - 3) * 2 + -qty / 4` already substituted to numbers, e.g. `(40 - 3) * 2 + -7 / 4`. Evaluate the string with +, -, *, /, unary minus, and parentheses, where division truncates toward zero, without using eval.
Amazon
November 29, 20260
0
0 solved
Pricing rules are stored as integer expressions like `(price - 3) * 2 + -qty / 4` already substituted to numbers, e.g. `(40 - 3) * 2 + -7 / 4`. Evaluate the string with +, -, *, /, unary minus, and parentheses, where division truncates toward zero, without using eval.
An onsite question in Amazon's style, framed around a promotions engine that stores discount formulas as text. Interviewers want a correct recursive descent or two-stack parser, correct precedence and associativity, and an explanation of why eval is unacceptable on seller-supplied input.
What the Interviewer Expects
- Tokenizes multi-digit numbers and skips whitespace
- Implements precedence: * and / bind tighter than + and -
- Gets left associativity right (8 - 3 - 2 = 3)
- Supports unary minus including before parentheses
- Truncates division toward zero, not floor
- Explains why eval is a security risk
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
- How would you add variables and precompile a formula evaluated millions of times?
- How would you add a power operator that is right associative?
- How would you report the position of a syntax error?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Non-negative integer literals, binary + - * /, unary + and -, parentheses, arbitrary spaces. Integer division truncates toward zero (so -7 / 4 = -1, unlike Python's // which gives -2). Reject inva...
High-Level Design
Use a grammar with one function per precedence level:
expression := term (('+'|'-') term)*term := factor (('*'|'/') factor)*factor := ('-'|'+') factor | '(' expression ')' | number
Loo...