📖 4 min read
Last updated on

Basic Calculator — Coding Interview Walkthrough


Hero Image for Basic Calculator — Coding Interview Walkthrough

You’re in a coding interview. The interviewer says: “Implement a basic calculator that evaluates a string expression with +, -, and parentheses.” No multiplication or division, just addition, subtraction, and nested parentheses. This is LeetCode #224, and the challenge is managing sign context through nested parentheses with a stack.

This walkthrough covers the stack-save pattern at ( and ), how to flush pending numbers, and the common parsing traps candidates fall into.


The Problem

Given a string s representing a valid mathematical expression with integers, +, -, (, ), and spaces, evaluate and return the result. The expression is guaranteed to be valid. (LeetCode #224)

Example 1

Input s = "1 + 1"

Output 2

Example 2

Input s = " 2-1 + 2 "

Output 3

Example 3

Input s = "(1+(4+5+2)-3)+(6+8)"

Output 23

Already comfortable with the solution? Practice it in a mock interview →

Expression '(1+(4+5))' with stack processing. Inner parenthesized subexpression highlighted, pop pointer at closing paren.

What Interviewers Are Actually Testing

SkillWhat Interviewers Observe
Stack for parenthesis contextDo you push (result, sign) onto the stack at each (?
Sign trackingDo you track the current sign and apply it to each number?
Multi-digit numbersDo you build multi-digit numbers character by character?
No eval()Do you implement parsing from scratch?
SpacesDo you skip spaces without breaking number parsing?

Step 1: Clarifying Questions

1. Can sub-expressions be nested arbitrarily deep? Yes, parentheses can nest to any depth.

2. Are there leading or trailing spaces? Yes, but they should be ignored.

3. Can there be adjacent operators like -- or +-? No, the expression is guaranteed valid. No adjacent operators.


Step 2: The Key Insight

When you enter a (, push the current running result and the current sign onto the stack, then reset. When you exit ), pop the saved result and sign, and combine: new_result = popped_result + popped_sign * result. This lets you process nested expressions as independent subproblems.


Step 3: Algorithm

  1. Track result, num, and sign (initially 1) as you iterate through the string.
  2. Digit: Build multi-digit numbers: num = num * 10 + int(ch).
  3. + or -: Flush pending number (result += sign * num), reset num, update sign.
  4. (: Push result and sign to stack, reset both.
  5. ): Flush pending number, then result = stack.pop() * result + stack.pop().
  6. End of string: Flush the last pending number.

Python Implementation

def calculate(s: str) -> int:
    stack = []
    result = 0
    num = 0
    sign = 1  # +1 or -1

    for ch in s:
        if ch.isdigit():
            num = num * 10 + int(ch)
        elif ch in ('+', '-'):
            result += sign * num
            num = 0
            sign = 1 if ch == '+' else -1
        elif ch == '(':
            # Save current state and reset
            stack.append(result)
            stack.append(sign)
            result = 0
            sign = 1
        elif ch == ')':
            result += sign * num
            num = 0
            result *= stack.pop()   # saved sign before this '('
            result += stack.pop()   # saved result before this '('
        # spaces are skipped implicitly

    result += sign * num
    return result

Time and Space Complexity

TimeSpace
Basic CalculatorO(n)O(n)

Single pass through the string. Stack depth equals the nesting depth of parentheses.


Common Interview Mistakes

  • Forgetting to flush num at each operator. When you see + or -, apply sign * num to result before resetting num. Don’t wait until the end.

  • Not flushing num at ). Similar to the operator case. Before combining with the stack values, apply the last pending num.

  • Building numbers wrong. Multi-digit numbers require num = num * 10 + int(ch), not just num = int(ch).

  • Using eval(). Never in an interview. Implement the parser manually.

  • Sign across parentheses. After a - followed by (, the sign inside the parentheses is negated. Pushing sign before the ( and multiplying by it after the ) handles this correctly.


What a Strong Candidate Sounds Like

“I’ll track a running result, a pending num, and the current sign. At + or -, I flush num * sign into result. At (, I push the current result and sign onto the stack and reset. At ), I flush the pending num, then combine with the stack: result = saved_sign * result + saved_result. Single pass, O(n) time, O(n) stack space.”


Example Interview Dialogue

Interviewer: Walk through (1+(4+5+2)-3)+(6+8).

Candidate: Starting with result=0, sign=1. Hit (: push (0, 1), reset result=0, sign=1. Read 1: num=1. Hit +: flush result=1, sign=1. Hit (: push (1, 1), reset result=0, sign=1. Read 4+5+2: result accumulates to 11. Hit ): pop sign=1, pop saved_result=1. result = 111 + 1 = 12. Hit -: sign=-1. Read 3: result = 12 + (-1)3 = 9. Hit ): pop sign=1, pop saved_result=0. result = 19 + 0 = 9. Hit +: sign=1. Hit (: push (9, 1), reset. Read 6+8 = 14. Hit ): result = 114 + 9 = 23. Final answer: 23.



Practice This in a Mock Interview

Basic Calculator is intimidating on the surface but elegant once you see the stack-save pattern at ( and ). Trace through (1+(4+5+2)-3)+(6+8) by hand before your interview to lock in the mechanics.

Start a mock interview for Basic Calculator on Intervu.

Further reading:

Practice Like It's the Real Interview

Get instant feedback on your approach, communication, and code — powered by AI.

Start a Mock Interview →