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
- Stack-based approach for basic calculator — handle nested parentheses with a stack storing sign and running result.
- Clean implementation — not just "it works" but readable, well-structured code.
- OOP extension design:
- Operator interface/abstract class with
precedenceandevaluate(a, b) - Strategy pattern or operator registry
- Open/Closed principle — add new operators without modifying the parser
- Operator interface/abstract class with
- Discuss trade-offs — recursive descent parser vs stack-based, extensibility vs simplicity.
Follow-ups
- How would you add support for unary minus (e.g.,
-3 + 5)? - How would you support variables (e.g.,
x + 3where x=5)? - What design pattern best fits the operator extension? (Strategy, Command, or Visitor?)
- How would you add support for functions like
max(3, 5)orsqrt(16)?