15% off all plans & roadmaps Use code

See plans

Basic Calculator

Updated

TL;DR: You must evaluate a string of digits, plus, minus and parentheses without using eval. Scan the string once, and at each open parenthesis push the outer total and sign onto a stack so the group can finish first.

Problem

Given a string s that represents a valid expression, implement a basic calculator that evaluates it. Return the result of the evaluation.

Note: You may not use any built-in function that evaluates a string as a math expression, such as eval().

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

Constraints

  • 1 <= s.length <= 3 * 10^5
  • s consists of digits, '+', '-', '(', ')', and ' '.
  • s represents a valid expression.
  • '+' is not used as a unary operation (for example "+1" or "+(2 + 3)" is invalid).
  • '-' may be used as a unary operation (for example "-1" or "-(2 + 3)" is valid).
  • There are no two consecutive operators in the input.
  • Every number and running calculation fits in a signed 32-bit integer.

Constraints that matter

  • The length can reach 3 * 10^5, so any method that rescans or rebuilds the string once per group costs O(n^2) on large nested inputs.
  • Nesting can go about n / 2 levels deep, so the saved state can need O(n) space. You need a stack, not a fixed set of variables.
  • Unary minus is allowed but unary plus is not. A sign comes only from a - placed before a number or a group, so one sign variable is enough.
  • Values fit in 32 bits, so plain int arithmetic is safe in Java, C++ and C#. Python integers never overflow.

View on LeetCode

Hints

Hint 1

This is expression evaluation with a stack.

Hint 2

Treat the innermost parentheses as a flat expression.

Solution

Intuition

This is expression evaluation with a stack. The whole expression is a sum of signed terms, and a parenthesis group is one term whose value comes from the expression inside it.

Picture a pile of sticky notes on a desk. Each open parenthesis writes the running total and its sign on a new note and places it on top. The stack is that pile of notes, and each closing parenthesis pulls the top note off to finish the outer sum.

What to notice: the group must be evaluated before it joins the outer total, yet the outer total is not finished. You must remember that total and the sign that applies to the group. Groups nest, so the most recently saved state must come back first. That is last in, first out order, which is what a stack gives you.

Once you see that, one left-to-right scan is enough. Digits build a number. An operator or a closing parenthesis finishes a term. An opening parenthesis saves the state, and a closing one restores it.

Watch the pattern animation

Worked example

Input: s = "(10-(2+3))+((4+5)-(6-7))+8"
Output: 23
Explanation: The group (10-(2+3)) evaluates to 5. The group ((4+5)-(6-7)) evaluates to 9 minus -1, which is 10. The total is 5 + 10 + 8, which is 23.

Approach 1: Brute force

Treat the innermost parentheses as a flat expression. Evaluate that group with a plain left-to-right pass over digits, + and -. Replace the group with its value in the string, then repeat until no parentheses remain. Most people write this first, and it is correct.

Steps

  1. Find the last ( in the string. It is the innermost open parenthesis.
  2. Find the first ) after it. Those two characters bound the innermost group.
  3. Evaluate the text between them with a flat pass. A - flips the sign of the next term, so --1 becomes +1.
  4. Replace the group, including both parentheses, with the value written as text.
  5. Repeat until no ( remains, then run the flat pass on the whole string.

Dry run

Start with (10-(2+3))+((4+5)-(6-7))+8.

Round 1: the last ( sits in (6-7), which evaluates to -1. The string becomes (10-(2+3))+((4+5)--1)+8.

Round 2: the last ( sits in (2+3), which evaluates to 5. The string becomes (10-5)+((4+5)--1)+8.

Round 3: the last ( sits before 4+5, which evaluates to 9. The string becomes (10-5)+(9--1)+8.

Round 4: 9--1 evaluates to 10, because two minus signs make a plus. The string becomes (10-5)+10+8.

Round 5: (10-5) evaluates to 5. The string becomes 5+10+8. No parentheses remain, so the flat pass returns 23.

Complexity

TimeO(n^2)
SpaceO(n)

Let n be the length of s. Each round removes one ( and never adds one, so there are at most n / 2 rounds. Each round scans the string to find the group, evaluates it, and builds a new string, which costs O(n) work. Multiplying about n / 2 rounds by O(n) work per round gives O(n^2) time, and the strings it builds use O(n) space.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def calculate(self, s: str) -> int:
        def eval_flat(t: str) -> int:
            # Digits, + and - only. A '-' flips the sign of the next term.
            total = 0
            sgn = 1
            num = 0
            in_num = False
            for ch in t:
                if ch.isdigit():
                    num = num * 10 + int(ch)
                    in_num = True
                else:
                    if in_num:
                        total += sgn * num
                        num = 0
                        in_num = False
                        sgn = 1
                    if ch == '-':
                        sgn = -sgn
            if in_num:
                total += sgn * num
            return total

        while '(' in s:
            i = s.rfind('(')
            j = s.index(')', i)
            value = eval_flat(s[i + 1:j])
            s = s[:i] + str(value) + s[j + 1:]
        return eval_flat(s)

The Expression Evaluation (RPN/Infix) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Expression Evaluation (RPN/Infix)

Part of Stack Patterns

Approach 2: One-pass stackOptimalExpression Evaluation (RPN/Infix)

What's slow in the brute force is the rework. Each round rescans the string, rebuilds it, and evaluates one group in isolation, so the outer text is copied again and again.

The insight that fixes it is that you never need to rebuild. When a group opens, push the outer total and sign onto a stack. When it closes, pop them and fold the group's value in. One left-to-right pass handles every nesting level.

Why it is correct. At every moment, the stack holds the partial total and sign of each unfinished group, from outermost to innermost. Closing a parenthesis applies the saved sign to the finished group and adds it to the waiting total, so the value is rebuilt exactly. No term is skipped or reordered, so the final result equals the value of the full expression.

Steps

  1. Keep result (the total so far), sign (1 or -1, the sign of the next term) and num (the number being read).
  2. On a digit, set num = num * 10 + digit.
  3. On + or -, add sign * num to result, set num to 0, then set sign to 1 for + or -1 for -.
  4. On (, push result, push sign, then set result to 0 and sign to 1.
  5. On ), add sign * num to result and set num to 0. Pop the sign and multiply result by it. Pop the outer result and add it.
  6. Skip spaces. At the end, return result + sign * num.

Dry run

Trace the table on the example. Each ) pops the sign first, because the sign was pushed second. After the row for the second ), the sign column still reads -1, but num is 0, so that stale sign adds nothing.

StepReadresultsignnumstack (bottom to top)
1(010[(0,1)]
21 then 00110[(0,1)]
3-10-10[(0,1)]
4(010[(0,1), (10,-1)]
52 then +210[(0,1), (10,-1)]
63213[(0,1), (10,-1)]
7) inner5, then -5, then 510[(0,1)]
8) outer510[]
9+510[]
10(010[(5,1)]
11(010[(5,1), (0,1)]
124 then +410[(5,1), (0,1)]
135 then )910[(5,1)]
14-9-10[(5,1)]
15(010[(5,1), (9,-1)]
166 then -6-10[(5,1), (9,-1)]
177 then )10-10[(5,1)]
18) group15-10[]
19+1510[]
2081518[]
endreturn result + sign * num2318[]

Complexity

TimeO(n)
SpaceO(n)

Let n be the length of s. The loop reads each character once, and every branch does constant work, so the scan costs O(n). Each ( pushes two values and each ) pops two, so the stack holds at most two values per open parenthesis. The nesting depth is at most about n / 2, so the stack uses O(n) space.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def calculate(self, s: str) -> int:
        stack = []  # saved (result, sign) pairs for outer levels
        result = 0
        sign = 1
        num = 0
        for ch in s:
            if ch.isdigit():
                num = num * 10 + int(ch)
            elif ch == '+':
                result += sign * num
                num = 0
                sign = 1
            elif ch == '-':
                result += sign * num
                num = 0
                sign = -1
            elif ch == '(':
                stack.append(result)
                stack.append(sign)
                result = 0
                sign = 1
            elif ch == ')':
                result += sign * num
                num = 0
                result *= stack.pop()
                result += stack.pop()
        return result + sign * num

Common mistakes

  • result += sign * digit inside the digit branch. This adds each digit as its own term, so 12 becomes 1 + 2. Only add sign * num when an operator or ) ends the number, and build num = num * 10 + digit on each digit.
  • Skipping the flush before ). Calling result *= stack.pop() directly drops the last number, such as the 3 in (2+3). Add sign * num and set num to 0 before any pop.
  • Popping the result before the sign. The stack holds the result first and the sign second, so the sign is on top. Pop the sign for the multiply, then pop the result for the add.
  • Forgetting to reset result and sign at (. The inner group then starts from the outer total, so 2-(3) gives the wrong answer. Push both values, then set result = 0 and sign = 1.
  • Dropping the saved sign. Writing result += saved_result without multiplying by the saved sign loses the minus in -(2+3). The popped sign must multiply the group before the outer result is added.
  • Building num without the * 10 step, so 123 is read as separate digits. Each digit must multiply the running number by 10 before it adds the new digit.

Edge cases

  • 1: no operator and no parenthesis. The final flush returns 1.
  • -2 + 1: a leading minus sets the sign to -1 before the first number. The expected output is -1.
  • (1): a group with one number and no operator. The expected output is 1.
  • 2-(5-6): a minus in front of a group that contains a minus. The expected output is 3.
  • ((((1)))): deep nesting. Each ( pushes two values, so the stack reaches 8 entries and unwinds back to empty.
  • 2-1 + 2: leading, trailing and inner spaces are skipped. The expected output is 3.

Follow-ups interviewers ask

What if the expression also had * and /?
Keep the same stack for parentheses, and add a term variable that holds the most recent product or quotient. On * or /, combine the next number with term instead of adding it to result. Java, C++, C# and Go truncate integer division toward zero, while Python's // floors, so match the rule your interviewer expects.
Can you use recursion instead of an explicit stack?
Yes. Write a function that reads from a shared index, calls itself on ( to evaluate the group, and returns the group's value on ). The call stack then plays the role of the explicit stack. Python's default recursion limit is about 1000, so inputs with deep nesting need the iterative version.
Can you do it in O(1) extra space?
Not with this method, because each open parenthesis needs a saved total and sign, and nesting can reach about n / 2. I am not aware of an O(1) extra space method that keeps O(n) time, so the stack is the answer to give in an interview.

Basic Calculator FAQ

What is the time complexity of Basic Calculator?

The one-pass stack solution runs in O(n) time, where n is the length of the string. Each character is handled once with constant work. The brute force that rebuilds the string after each group takes O(n^2) time.

Why use a stack for Basic Calculator?

Each ( suspends the outer total and sign, and each ) restores them. Groups close in the reverse order they open, which is the order a stack returns items. That match is why the stack handles nesting with one pass.

Can Basic Calculator be solved in O(1) extra space?

Not with the stack method, because each open parenthesis needs a saved total and sign, and nesting can reach about n / 2. I am not aware of an O(1) extra space method that keeps O(n) time, so the stack is the standard answer.

How does Basic Calculator handle a minus sign in front of a parenthesis?

The - sets sign to -1 before the (. The ( pushes that sign with the outer total, and the matching ) multiplies the group by it. So -(2+3) evaluates to -5.

Why does the string replacement method fail for Basic Calculator?

It rebuilds and rescans the whole string once per group. With up to 3 * 10^5 characters and deep nesting, the worst case reaches tens of billions of character operations, which is too slow.

Asked at

See which companies ask this — Pro

Practise it