All questions
Hard2026-08-04

Basic Calculator with OOP Extension

Company
Amazon
Role

SDE-2

Round

Round 2 (Coding + Design)

StackParsingOOPDesign Patterns

Problem Statement

Implement a basic calculator to evaluate a string expression containing:

  • Non-negative integers
  • +, - operators
  • ( and ) parentheses
  • Spaces (ignore them)

Then, extend the solution in an object-oriented manner to support:

  • Multiplication and division (with proper precedence)
  • Custom operators that can be plugged in

Constraints

  • 1 <= expression.length <= 3 * 10^5
  • Expression is guaranteed to be valid
  • No leading zeros in numbers
  • Result fits in a 32-bit integer
  • The OOP extension should allow adding new operators without modifying existing code

Example

Basic:

Input:  "(1+(4+5+2)-3)+(6+8)"
Output: 23

Extended with * and /:

Input:  "2+3*4-6/2"
Output: 11  (3*4=12, 6/2=3, then 2+12-3=11)

What the Interviewer Expects

  1. Stack-based approach for basic calculator — handle nested parentheses with a stack storing sign and running result.
  2. Clean implementation — not just "it works" but readable, well-structured code.
  3. OOP extension design:
    • Operator interface/abstract class with precedence and evaluate(a, b)
    • Strategy pattern or operator registry
    • Open/Closed principle — add new operators without modifying the parser
  4. Discuss trade-offs — recursive descent parser vs stack-based, extensibility vs simplicity.

Follow-ups

  1. How would you add support for unary minus (e.g., -3 + 5)?
  2. How would you support variables (e.g., x + 3 where x=5)?
  3. What design pattern best fits the operator extension? (Strategy, Command, or Visitor?)
  4. How would you add support for functions like max(3, 5) or sqrt(16)?
🧠

No solution provided

Think through it. That's how you build real interview muscle.

Share: