Evaluate Spotlight Calculator Expressions With Precedence and Parentheses

Last updated: November 29, 2026

Quick Overview

Spotlight evaluates typed arithmetic. Implement evaluate(expr) for integers with +, -, *, /, unary minus and parentheses, where division truncates toward zero, without using eval.

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

0

0

0 solved


Spotlight evaluates typed arithmetic. Implement evaluate(expr) for integers with +, -, *, /, unary minus and parentheses, where division truncates toward zero, without using eval.

A classic Apple onsite parsing question with a Spotlight framing. Interviewers want a principled approach, either recursive descent or a two-stack shunting-yard, and they probe unary minus and truncating division, which trip up most candidates.

What the Interviewer Expects
  • Tokenize numbers, operators and parentheses, ignoring spaces
  • Use a grammar with expression, term and factor levels
  • Handle unary minus inside factor
  • Truncate division toward zero, not floor
  • Raise clear errors on malformed input and division by zero
Key Topics to Cover
recursive descent
parsing
operator precedence
tokenization
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.
  • Support decimals and percent like Spotlight does.
  • Give a helpful error position for '3 + * 4'.
  • Evaluate incrementally as the user types each character.
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

Input: a string such as -(2 + 3) * 4 - 7 / 2. Output: an int. Operators: binary + - * /, unary -, parentheses. Division truncates toward zero (so -7 / 2 is -3). Malformed input raises ValueError...

High-Level Design

Tokenize with a regex into integers and single-character symbols. Parse with three mutually recursive functions over a token index: expr := term (('+'|'-') term)*, `term := factor (('*'|'/') factor)...


Submit Your Answer
Markdown supported