Magicsheet logo

Basic Calculator

Hard
53.9%
Updated 6/1/2025

Basic Calculator

What is this problem about?

The "Basic Calculator interview question" is a high-stakes algorithmic challenge that requires you to parse and evaluate a mathematical expression string. The expression can contain non-negative integers, the operators + and -, and parentheses ( and ). This is a "Hard" difficulty problem because it requires handling nested logic and managing the signs of numbers across different scopes.

Why is this asked in interviews?

Tech giants like Google, Meta, and Amazon ask the "Basic Calculator coding problem" to see if a candidate can manage complex state and recursion. It's a test of attention to detail—handling whitespace, multi-digit numbers, and the impact of a minus sign before a parenthesis (which flips all signs inside). It assesses a candidate's ability to implement a simplified version of an expression evaluator or compiler.

Algorithmic pattern used

This problem is typically solved using the Stack or Recursion pattern.

  1. Iterative with Stack: Use a stack to save the current "global" result and the current sign whenever you encounter an opening parenthesis (.
  2. Sign Management: Keep track of the current running result and the sign of the next number (e.g., 1 for + and -1 for -).
  3. Parentheses: When you hit ), pop the sign and the previous result from the stack and combine them with the result of the expression inside the parentheses.

Example explanation

Expression: 1 - (2 + 3)

  1. 1: Result = 1, Sign = 1.
  2. -: Set Sign = -1.
  3. (: Push Result (1) and Sign (-1) to stack. Reset Result = 0, Sign = 1.
  4. 2: Result = 2.
  5. +: Set Sign = 1.
  6. 3: Result = 2 + 3 = 5.
  7. ): Pop Sign (-1) and Previous Result (1). New Result = 1+(1imes5)=41 + (-1 imes 5) = -4.

Common mistakes candidates make

  • Multi-digit numbers: Forgetting to process digits in a loop (e.g., "123" is 1imes100+2imes10+31 imes 100 + 2 imes 10 + 3) and instead only reading single characters.
  • Sign Confusion: Not properly distributing the negative sign across parentheses.
  • Whitespace: Forgetting to skip spaces in the input string.

Interview preparation tip

Master the "Stack interview pattern" for expression parsing. Practice the "Basic Calculator II" (with multiplication/division) and "Basic Calculator III" to see how the complexity evolves. The key is to maintain a clear mental model of the "current context" vs the "previous context."

Similar Questions