Evaluate Surge Pricing Formulas With Variables and Parentheses
Last updated: November 29, 2026
Quick Overview
Pricing analysts write fare formulas such as `base + surge * (per_mile * miles - discount)`. Given a formula string and a dict of variable values, evaluate it with standard precedence, parentheses and unary minus, without using eval.
Uber
November 29, 20260
0
0 solved
Pricing analysts write fare formulas such as `base + surge * (per_mile * miles - discount)`. Given a formula string and a dict of variable values, evaluate it with standard precedence, parentheses and unary minus, without using eval.
An Uber onsite parsing question related to configurable pricing rules. Interviewers check whether you can tokenize cleanly, respect precedence and associativity, and structure the parser so it is easy to extend.
What the Interviewer Expects
- Tokenizes numbers, identifiers, operators and parentheses, skipping spaces
- Uses recursive descent with expression, term and factor levels
- Applies left associativity for minus and divide
- Supports unary minus
- Reports unknown variables and malformed input with clear errors
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 function calls such as min(a, b) and max(a, b).
- How would you compile the formula once and evaluate it for millions of trips?
- How would you guard against division by zero or runaway nesting?
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: formula string with numbers (int or decimal), identifiers,
+ - * /, parentheses, spaces; and a variables dict. - Output: numeric result as float.
- No
eval; errors for unknown names or ba...
High-Level Design
Split the work into a tokenizer and a parser. The tokenizer uses one regex to produce numbers, names and single-character symbols. The parser follows the grammar:
expr := term (('+' | '-') term)*...