Evaluate Ad Bid Formulas With Parentheses and Unary Minus

Last updated: November 29, 2026

Quick Overview

Given an arithmetic formula string with non-negative integers, +, -, *, /, parentheses, spaces, and unary minus (for example -(2+3)*4), evaluate it with standard precedence and integer division truncating toward zero, without using eval.

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

0

0

0 solved


Given an arithmetic formula string with non-negative integers, +, -, *, /, parentheses, spaces, and unary minus (for example -(2+3)*4), evaluate it with standard precedence and integer division truncating toward zero, without using eval.

Meta's ads systems let advertisers and internal tools express bid adjustments as formulas, and a full expression evaluator is a recurring Hard onsite problem. The interviewer is looking for a clean recursive descent parser with correct precedence, associativity, and unary handling.

What the Interviewer Expects
  • Define a grammar with expression, term, and factor levels
  • Implement left-associative + and -, then * and /
  • Handle unary minus at the factor level
  • Truncate division toward zero, not floor
  • Skip whitespace and parse multi-digit numbers
Key Topics to Cover
recursive descent parsing
stack
operator precedence
string parsing
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
  • How would you add exponentiation with right associativity?
  • How would you support variables like base_bid * 1.2?
  • How would you report a syntax error with its position?
  • How would you do this iteratively with two stacks?
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
  • Tokens: integers, + - * / ( ), spaces. Input is valid and intermediate results fit in 64 bits.
  • * and / bind tighter than + and -; operators of equal precedence are left associative.
  • A ...
High-Level Design

Grammar:

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

Strip spaces first, then use an index into the string....


Submit Your Answer
Markdown supported