Basic Calculator solution explained

Basic Calculator asks you to evaluate a string containing non-negative integers, plus, minus, parentheses and spaces, without calling eval. The one-pass answer keeps a running total and the sign of the next number; at an opening parenthesis it pushes the total and the sign in front of the parenthesis onto a stack and starts fresh, and at a closing one it folds the inner result back in. That runs in O(n) time with O(depth) extra space.

By Published 9 min read

The task, restated

You receive a string that is a valid arithmetic expression and must return its integer value. It can contain non-negative whole numbers of any number of digits, the operators + and -, round brackets nested to any depth, and spaces anywhere. A minus sign may also act as a negation, either at the very start or immediately after an opening bracket, as in -(4 + 1) or 3 - (-2). There is no multiplication or division in this version, and you may not hand the string to a built-in evaluator.

Examples made up for this page
ExpressionValueWhat it exercises
1 + 2 - 30Left to right, no brackets
12 - (4 + 5) + 14A minus in front of a bracket flips everything inside
-(3 - 10)7Unary minus applied to a whole group
2 - (5 - (1 - 4))-6Nested signs: the inner group is -3, the middle is 8
1-(-2)3Unary minus right after an opening bracket, no spaces
307 307Multi-digit number with surrounding spaces
Examples made up for this page. Scroll sideways on a small screen.

Confirm the grammar before you start, because the follow-up versions change it. Is the input always valid? Can + also be unary? Do numbers fit in a 32-bit integer, or should you not worry about overflow? Is there * or / in this version? Your answers decide how much defensive code you need.

What it tests

Expression evaluation shows up in interviews because it mixes parsing, a stack and careful state handling, and because there are several valid approaches to compare. The interviewer watches for three things: whether you read multi-digit numbers correctly, whether you see that a minus in front of a bracket negates the whole group, and whether you can explain what each stack entry means. The family has a few well-known members:

  • This version: plus, minus and brackets. A stack of saved totals and signs is enough.
  • **With * and / but no brackets:** precedence matters but nesting does not; a stack of pending terms solves it in one pass.
  • Everything together: brackets plus all four operators. Use recursion on brackets with the term stack inside, or the shunting-yard algorithm.
  • Tokens already split, in postfix order: reverse Polish notation, the easiest of the set, a single stack of numbers.

A slow reference: collapse the innermost brackets

Find the first closing bracket; the last opening bracket before it encloses a group with no brackets inside. Evaluate that flat group left to right, write its value back into the string in place of the group, and repeat until no brackets remain. Signs can pile up after a substitution, as when 1-(-2) becomes 1--2, so the flat evaluator treats each minus as a flip of the pending sign. Each round rewrites the string, so the worst case is O(n²), but the logic is easy to trust, which makes it a good oracle for testing.

def evaluate_flat(expr):
    total, sign, i, n = 0, 1, 0, len(expr)
    while i < n:
        ch = expr[i]
        if ch == "-":
            sign = -sign
            i += 1
        elif ch == "+" or ch == " ":
            i += 1
        else:
            j = i
            while j < n and "0" <= expr[j] <= "9":
                j += 1
            total += sign * int(expr[i:j])
            sign = 1
            i = j
    return total


def calculate_slow(s):
    while "(" in s:
        close = s.index(")")
        start = s.rindex("(", 0, close)
        inner = evaluate_flat(s[start + 1:close])
        s = s[:start] + str(inner) + s[close + 1:]
    return evaluate_flat(s)
Python: innermost-first rewriting. Correct, quadratic.

The key observation

Without brackets, the expression is a sum of signed numbers: 12 - 4 + 1 is 12 + (-4) + (+1). So you only need a running total and the sign that applies to the number being read. Brackets add one wrinkle: the sign in front of an opening bracket applies to the entire group. When you reach an opening bracket, you cannot finish the outer sum yet, so you save two things, the total so far and the sign in front of the bracket, then evaluate the group from scratch. At the matching closing bracket, the outer total becomes saved total + saved sign times the group's value. Nested brackets simply push more pairs.

Optimal approach: running total with a stack of saved states

def calculate(s):
    total, sign, num = 0, 1, 0
    saved = []  # (total before the bracket, sign in front of it)
    for ch in s:
        if "0" <= ch <= "9":
            num = num * 10 + int(ch)
        elif ch == "+" or ch == "-":
            total += sign * num
            num = 0
            sign = 1 if ch == "+" else -1
        elif ch == "(":
            saved.append((total, sign))
            total, sign = 0, 1
        elif ch == ")":
            total += sign * num
            num = 0
            outer_total, outer_sign = saved.pop()
            total = outer_total + outer_sign * total
    return total + sign * num
Python: one pass, the stack holds one pair per open bracket.
function calculate(s) {
  let total = 0;
  let sign = 1;
  let num = 0;
  const saved = [];
  for (const ch of s) {
    if (ch >= "0" && ch <= "9") {
      num = num * 10 + (ch.charCodeAt(0) - 48);
    } else if (ch === "+" || ch === "-") {
      total += sign * num;
      num = 0;
      sign = ch === "+" ? 1 : -1;
    } else if (ch === "(") {
      saved.push([total, sign]);
      total = 0;
      sign = 1;
    } else if (ch === ")") {
      total += sign * num;
      num = 0;
      const [outerTotal, outerSign] = saved.pop();
      total = outerTotal + outerSign * total;
    }
  }
  return total + sign * num;
}
JavaScript: the same state machine; char codes avoid parsing each digit as a string.

Unary minus needs no special case. At the start of the string, or just after an opening bracket, total and num are both 0, so reading a minus adds 0 to the total and sets the sign to -1 for the next number or group. Spaces fall through every branch and are ignored. The final line adds the last number, which has no operator after it to trigger the fold.

Trace: 2 - (5 - (1 - 4))

State after each meaningful character
CharactertotalsignnumStack
20+12[]
-2-10[]
(0+10[(2, -1)]
50+15[(2, -1)]
-5-10[(2, -1)]
(0+10[(2, -1), (5, -1)]
10+11same
-1-10same
41-14same
)5 + (-1)(-3) = 8-10[(2, -1)]
)2 + (-1)(8) = -6-10[]
State after each meaningful character. Scroll sideways on a small screen.

At the first closing bracket the inner total is 1 - 4 = -3; the saved pair (5, -1) turns that into 5 - (-3) = 8. The second closing bracket folds 8 into the outer pair (2, -1), giving -6. The leftover sign of -1 is harmless because num is 0 when the loop ends.

Follow-up: adding * and /

When multiplication and division appear (without brackets), keep a list of terms that will be summed at the end. Read a number, then look at the operator that came before it: plus pushes the number, minus pushes its negation, times replaces the last term with the product, and divide replaces it with the quotient. Division usually truncates toward zero. Python's // floors instead, so -7 // 2 is -4 where the expected answer is -3; divide the absolute values and restore the sign, as below. In JavaScript, Math.trunc(a / b) does the same job for numbers in the safe integer range. To support brackets as well, recurse at each opening bracket and treat the returned value as a number.

def calculate_with_products(s):
    terms, num, op = [], 0, "+"
    for ch in s + "+":
        if "0" <= ch <= "9":
            num = num * 10 + int(ch)
        elif ch in "+-*/":
            if op == "+":
                terms.append(num)
            elif op == "-":
                terms.append(-num)
            elif op == "*":
                terms.append(terms.pop() * num)
            else:
                top = terms.pop()
                q = abs(top) // num
                terms.append(q if top >= 0 else -q)
            op, num = ch, 0
    return sum(terms)
Python: four operators, no brackets, truncating division.

Time and space

n characters, bracket depth d
ApproachTimeExtra space
Innermost-first rewritingO(n²) worst caseO(n) for the rebuilt strings
Running total with a saved-state stackO(n)O(d)
Recursive descent, one call per bracketO(n)O(d) call stack
Term stack for * and /, no bracketsO(n)O(n) terms
n characters, bracket depth d. Scroll sideways on a small screen.

Edge cases

  • A single number, possibly with spaces around it: the loop never folds, and the final line returns it.
  • A unary minus at the very start, and directly after an opening bracket.
  • Deep nesting such as ((((7)))): the stack grows to the depth and unwinds cleanly.
  • Large numbers: Python integers do not overflow; in JavaScript, values beyond 2 to the 53rd power lose precision, so mention it if the constraints allow such values.
  • Spaces between the digits of what looks like one number, such as 1 2. Ask whether that can happen; the one-pass version above would read it as 12.

Mistakes to avoid

  • Reading one character as one number, so 12 becomes 1 and 2.
  • Forgetting to add the final number after the loop.
  • Applying the minus in front of a bracket only to the first number inside it.
  • Resetting the sign but not num at a closing bracket, so the last inner number is counted twice.
  • Using Python's // for truncating division in the follow-up and getting negative quotients wrong.
  • Calling eval, which the problem forbids and which would be a security risk on untrusted input anyway.

How to explain it out loud

Fictional example

Explaining what the stack stores
Candidate
Without brackets this is just a sum of signed numbers, so I keep a total, the sign for the next number, and the number I'm reading digit by digit.
Candidate
At an opening bracket I push the total so far and the sign in front of the bracket, then reset. At the closing bracket the new total is the saved total plus the saved sign times the inner result.
Candidate
Unary minus works for free, because total and num are zero at those points. One pass, linear time, and the stack is only as deep as the bracket nesting.

Decode String uses the same save-and-restore stack, with a repeat count and a partial string in place of a total and a sign. Implement Queue Using Stacks is a lighter stack exercise focused on amortized cost rather than parsing. Valid Parentheses checks bracket structure only, and is a natural warm-up before this one.

Natively for practice sessions

Parsing questions go wrong in small ways, so it helps to compare your state machine with another one. While you practice on a Mac or Windows PC, Natively can read the prompt from a screenshot and write an approach with code, or give a coding hint through its Code hint action when unary minus has you stuck. The session transcript shows whether you explained the saved pair clearly. See the AI interview assistant page.

Questions people ask

How do you solve Basic Calculator?

Keep a running total, the sign of the next number, and the number being read. At an opening bracket push the total and the sign in front of the bracket, then reset; at the closing bracket combine them as saved total plus saved sign times the inner result.

How do you handle unary minus in Basic Calculator?

With the running-total approach it needs no special case. At the start of the string or right after an opening bracket the total and number are zero, so a minus simply sets the sign for what follows.

What is the time complexity of Basic Calculator?

The stack solution reads each character once, so it is O(n) time, with extra space proportional to the bracket nesting depth.

How do you handle multiplication and division?

Keep a list of terms. Plus and minus push a signed number, times and divide combine with the last term immediately, and the answer is the sum of the terms. Truncate division toward zero.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP