15% off all plans & roadmaps Use code
See plansBasic Calculator III
- LeetCode 772
- Hard
- Stack Patterns
- Expression Evaluation (RPN/Infix)
Updated
TL;DR: Evaluate an expression with +, -, *, /, and parentheses, respecting precedence and truncating division toward zero. Use one left-to-right pass with a stack: `*` and `/` combine with the previous term right away, and each `(` saves the outer state on a second stack.
Problem
You are given a string s that represents a valid mathematical expression. The expression can contain non-negative integers, the operators +, -, *, /, parentheses ( and ), and spaces.
Evaluate the expression and return its result as an integer. Integer division truncates toward zero. You may not use built-in functions that evaluate strings as expressions, such as eval().
Example 1
Input: s = "18 - (4 + 2 * (6 - 3)) / 2" Output: 13
Constraints
1 <= s.length <= 10^4sconsists of digits, the operators+,-,*,/, parentheses(and), and spaces.- The given expression is always valid.
Constraints that matter
- Length up to 10^4 means one pass over the string is required. Rewriting the string after every operator can cost O(n^2) work.
- Parentheses can nest about n/2 levels deep. Recursion in Python would hit the default limit near 1000, so keep the nesting on an explicit stack.
- Every operator is binary and the input is valid, so you never see unary minus or division by zero. Handle only the operators listed.
- Integer division must truncate toward zero. Python's
//floors, so-7 // 2gives -4 instead of -3.
Hints
Hint 1
The problem is infix expression evaluation with precedence and grouping.
Hint 2
Scan the string once and keep three pieces of state: the terms of the current level, the operator waiting to apply to the current number, and the number being built.
Solution
Intuition
The problem is infix expression evaluation with precedence and grouping. Multiplication and division bind tighter than addition and subtraction, and parentheses override both. A stack handles this well because it holds results that are waiting for a later operator.
Picture a pile of sticky notes, where each open parenthesis writes the outer terms and pending operator on a note and starts a clean sheet. The saved stack is that pile, and the current terms are the sheet on top.
The key observation is that a subtraction is an addition of a negative term. An expression then becomes a sum of signed terms, and each term is a product or quotient of numbers. You only need to keep the terms of the current level and sum them at the end.
When you read * or /, the previous term is still open. Pop it, combine it with the current number, and push the result back. When you read + or -, the previous term is closed, so you push it with its sign. This is why precedence falls out of the order of operations without any table.
Parentheses need a memory of the outer level. On (, save the current terms and the pending operator, then start a fresh level. On ), sum the inner terms, restore the outer level, and treat the sum as one number.
Worked example
Input: s = "18 - (4 + 2 * (6 - 3)) / 2" Output: 13 Explanation: The inner group (6 - 3) is 3, so 2 * 3 is 6. The outer group (4 + 6) is 10, and 10 / 2 is 5. Finally 18 - 5 is 13.
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 infographicSolution pattern
Expression Evaluation (RPN/Infix)
Part of Stack Patterns
Approach 1: One pass with a stack of saved framesOptimalExpression Evaluation (RPN/Infix)
Scan the string once and keep three pieces of state: the terms of the current level, the operator waiting to apply to the current number, and the number being built. A digit extends the number. An operator applies the waiting operator to the number, then becomes the new waiting operator. The naive version rewrites the string again and again, and each rewrite costs a full copy, so this approach never rewrites anything.
A * or / pops the last term and replaces it with the product or quotient. That merges the higher-precedence work into a single term immediately. A + or - pushes the number as a new term, with a minus sign for subtraction, and the sum is taken at the end of the level.
For parentheses, push the current terms and the waiting operator onto a second stack before entering the group. When ) appears, finish the group, sum its terms, pop the saved frame, and make that sum the current number. The outer waiting operator then applies to it as if it were a plain number.
Why it is correct. At every step, the terms on the stack plus the pending operator's effect equal the value read so far at this level. Folding a multiply or divide into the last term is safe, because later input cannot bind tighter than that operator already did. A closing parenthesis collapses its whole group into one number, and the saved frame restores the outer operator, so the group behaves as one value.
Steps
- Set
stackto an empty list of terms,opto+, andnumto 0. Create an emptysavedstack for outer frames. - For each character, skip spaces.
- On a digit, set
num = num * 10 + digit. - On
(, push(stack, op)ontosaved, then resetstackto empty,opto+, andnumto 0. - On
+,-,*,/, or), applyoptonum: pushnumfor+, push-numfor-, pop and multiply for*, pop and divide for/. - If the character is
), setnumto the sum ofstack, then restorestackandopfrom the top ofsaved. Otherwise setopto the character andnumto 0. - After the loop, apply
optonumonce more, because the last number has no closing operator. - Return the sum of
stack.
Dry run
Trace on 18 - (4 + 2 * (6 - 3)) / 2. Each row shows the state after the character is processed. saved lists the outer frames as (terms, op).
| Step | Character | num | op | stack | saved |
|---|---|---|---|---|---|
| 1 | 1, 8 | 18 | + | [] | [] |
| 2 | - | 0 | - | [18] | [] |
| 3 | ( | 0 | + | [] | ([18], -) |
| 4 | 4 | 4 | + | [] | ([18], -) |
| 5 | + | 0 | + | [4] | ([18], -) |
| 6 | 2 | 2 | + | [4] | ([18], -) |
| 7 | * | 0 | * | [4, 2] | ([18], -) |
| 8 | ( | 0 | + | [] | ([18], -), ([4, 2], *) |
| 9 | 6 | 6 | + | [] | ([18], -), ([4, 2], *) |
| 10 | - | 0 | - | [6] | ([18], -), ([4, 2], *) |
| 11 | 3 | 3 | - | [6] | ([18], -), ([4, 2], *) |
| 12 | ) | 3 | * | [4, 2] | ([18], -) |
| 13 | ) | 10 | - | [18] | [] |
| 14 | / | 0 | / | [18, -10] | [] |
| 15 | 2 | 2 | / | [18, -10] | [] |
| 16 | end | 0 | / | [18, -5] | [] |
At row 12, the ) applies - with 3 to give [6, -3], sums to 3, and restores the frame [4, 2] with *. At row 13, * pops 2 and pushes 6, giving [4, 6], which sums to 10, and the frame restore gives [18] with -. Row 14 applies - with 10. The final step applies / with 2 to get -5, and the sum is 18 + (-5) = 13.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the length of s. Each character is read once, and each digit extends num in constant time. Each number is pushed once and popped at most once, and each ( and ) pushes and pops one frame, so the total work is a constant times n. The stacks hold at most one term per number and one frame per open parenthesis, so their size is at most n.
PythonTested in our runner
from typing import List, Optional
class Solution:
def calculate(self, s: str) -> int:
def apply(op: str, num: int, stack: List[int]) -> None:
if op == '+':
stack.append(num)
elif op == '-':
stack.append(-num)
elif op == '*':
stack.append(stack.pop() * num)
else:
a = stack.pop()
q = abs(a) // abs(num) # truncate toward zero
stack.append(q if (a < 0) == (num < 0) else -q)
stack: List[int] = []
saved: List[tuple] = []
op = '+'
num = 0
for c in s:
if c == ' ':
continue
if c.isdigit():
num = num * 10 + int(c)
elif c == '(':
saved.append((stack, op))
stack, op, num = [], '+', 0
else:
apply(op, num, stack)
if c == ')':
num = sum(stack)
stack, op = saved.pop()
else:
op = c
num = 0
apply(op, num, stack)
return sum(stack)Common mistakes
- Setting
op = cbefore applying the old operator. The pendingopthen multiplies or adds the wrong number. Apply first, then store the new operator. - Forgetting
num = 0after an operator. The next number then starts from the old value, so12 + 3could read as 15 + 3. - Missing the final flush. The last number has no operator after it, so
apply(op, num, stack)must run once after the loop. - Writing
op = ')'in the closing branch. A)should restore the saved outer operator, not become the pending operator. - Treating a space as an operator. Digits keep building across spaces until a real operator appears, so skip spaces before the operator check.
- Using Python's
//orint(a / b)for division.//floors negatives, so-7 // 2is -4, andint(a / b)goes through a float. Compute the quotient from absolute values and apply the sign.
Edge cases
- A single number such as
"7"returns 7 with no operators and no frames. - Nested parentheses such as
"((((5))))"return 5 and leave no saved frames behind. - Subtraction of a negative group such as
"1-(2-3)"returns 2, which checks that the outer sign applies to the whole group. - Truncation toward zero such as
"7-10/3"returns 4, because 10 / 3 is 3, not 4. - Negative division such as
"0-7/2"returns -3, because 7 / 2 truncates to 3 before the subtraction. A floor-based answer would give -4. - A long chain such as
"1+1+1+...+1"with 5000 ones returns 5000 and checks that the stack handles many terms.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Basic Calculator III, with how to answer them.
Unlock the follow-upsBasic Calculator III FAQ
What is the time complexity of Basic Calculator III?
The time complexity is O(n), where n is the length of the string. Each character is read once, and each number and each parenthesis causes a constant amount of stack work. The total work is a constant times n.
Why use a stack for Basic Calculator III?
A stack holds terms that are waiting for a later operator or a closing parenthesis. Multiplication and division can merge with the last term at once, and parentheses can save the outer state. This resolves precedence in one pass without building a parse tree.
Can Basic Calculator III be solved in O(1) extra space?
No, not in the general case. A deep nesting such as ((((1)))) needs one saved frame per open parenthesis, and a long sum needs one stored term per number. Both grow with n in the worst case, so the space is O(n).
What is the Python gotcha with division in this problem?
Python's // rounds toward negative infinity, and int(a / b) goes through a float. For example, -7 // 2 is -4 instead of the required -3. Compute the quotient from absolute values and then apply the sign.
Asked at
See which companies ask this — Pro
Related problems
- Basic Calculator · same technique: Expression Evaluation (RPN/Infix)
- Evaluate Reverse Polish Notation · same technique: Expression Evaluation (RPN/Infix)
- Basic Calculator II · same technique: Expression Evaluation (RPN/Infix)
- Largest Rectangle in Histogram · same pattern: Stack Patterns
- Reconstruct Itinerary · same pattern: Stack Patterns
- Maximum Frequency Stack · same pattern: Stack Patterns
- Longest Valid Parentheses · same pattern: Stack Patterns
- Maximal Rectangle · same pattern: Stack Patterns
- Min Stack · same pattern: Stack Patterns
- Daily Temperatures · same pattern: Stack Patterns