Skip to main content

Basic Calculator - Solution & Explanation

HardMathStringStackRecursion25 min readAsked at: Amazon, Microsoft, Apple +22
Practice this problem

Problem Statement

Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, 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 * 105
  • s consists of digits, '+', '-', '(', ')', and ' '.
  • s represents a valid expression.
  • '+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid).
  • '-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid).
  • There will be no two consecutive operators in the input.
  • Every number and running calculation will fit in a signed 32-bit integer.

Approach Overview

Problem Overview: Evaluate a string expression containing integers, +, -, parentheses, and spaces. You must correctly handle nested parentheses and operator precedence while scanning the string.

Approach 1: Iterative Stack Evaluation (O(n) time, O(n) space)

This approach scans the expression from left to right while maintaining the current number, current sign, and a running result. When encountering digits, you build the number. When encountering + or -, you finalize the previous number by applying the stored sign. Parentheses introduce a new evaluation scope, so you push the current result and sign onto a stack. When a closing parenthesis appears, compute the inner expression and combine it with the previous state popped from the stack. Each character is processed once, giving O(n) time complexity and O(n) auxiliary space for nested parentheses.

Approach 2: Recursive Expression Parsing (O(n) time, O(n) space)

The recursive method treats each parenthesized expression as a subproblem. While iterating through the string, digits build numbers and signs update the running result. When an opening parenthesis appears, recursively evaluate the substring until the matching closing parenthesis. The returned value becomes the current number in the outer expression. This mirrors how compilers parse arithmetic expressions and is a natural fit for problems involving nested structures in a string. The recursion stack may grow up to the depth of parentheses, so space complexity is O(n) in the worst case.

Recommended for interviews: The iterative stack solution is usually expected because it demonstrates strong control over expression parsing and stack-based state management. Interviewers often look for the insight that each parenthesis creates a new evaluation frame that can be saved and restored with a stack. The recursive approach is equally valid and sometimes easier to reason about, especially if you already think of the expression as nested subproblems. Both rely on concepts from math, stack, and recursion, and both achieve optimal O(n) time complexity since every character in the expression is processed exactly once.

Approach 1: Iterative with Stack

This approach uses a stack to handle the parentheses. We iterate over the string, using a stack to track the signs. We also build numbers on-the-fly to consider multi-digit numbers. Each time we encounter a closing parenthesis, we compute the resolved values until we reach an opening parenthesis.

In this solution, we use a stack to store results and signs before entering a set of parentheses. As we iterate over the expression, we update the result according to the sign, and when we encounter a closing parenthesis, we pop from the stack and multiply with the sign to maintain order.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of the string, as we iterate over it once.
Space Complexity: O(n) for the stack used to store intermediate results.

Try this approach in the editor →

Approach 2: Recursive

In this approach, we define a recursive function that processes the expression by evaluating parts of the expression until the end of the string or a closing parenthesis is encountered. The recursion allows "diving into" parentheses with adjusted state that mirrors stack behavior.

This C solution employs a recursive strategy to compute bracketed sub-expressions by evaluating subsequent numbers and operators in a controlled, isolated scope. Each recursive call takes over when an open bracket is encountered, emulating stack behavior implicitly.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of string as operations are done in a linear pass.
Space Complexity: O(n) due to recursive call stack overhead.

Try this approach in the editor →

Approach 3: Stack

We use a stack stk to save the current calculation result and operator, a variable sign to save the current sign, and a variable ans to save the final calculation result.

Next, we traverse each character of the string s:

  • If the current character is a number, we use a loop to read the following consecutive numbers, and then add or subtract it to ans according to the current sign.
  • If the current character is '+', we change the variable sign to positive.
  • If the current character is '-', we change the variable sign to negative.
  • If the current character is '(', we push the current ans and sign into the stack, and reset them to empty and 1, and start to calculate the new ans and sign.
  • If the current character is ')', we pop the top two elements of the stack, one is the operator, and the other is the number calculated before the bracket. We multiply the current number by the operator, and add the previous number to get the new ans.

After traversing the string s, we return ans.

The time complexity is O(n), and the space complexity is O(n), where n is the length of the string s.

Code

Python

Java

C++

Go

TypeScript

C#

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Iterative with Stack

Time Complexity: O(n), where n is the length of the string, as we iterate over it once.
Space Complexity: O(n) for the stack used to store intermediate results.

Recursive

Time Complexity: O(n), where n is the length of string as operations are done in a linear pass.
Space Complexity: O(n) due to recursive call stack overhead.

Stack—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Iterative Stack EvaluationO(n)O(n)General case with nested parentheses. Preferred interview solution.
Recursive Expression ParsingO(n)O(n)When recursive parsing feels more natural for nested expressions.

Video Solution

BASIC CALCULATOR | LEETCODE # 224 | PYTHON SOLUTION • Cracking FAANG • 46,921 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Basic Calculator easy or hard?
Basic Calculator is classified as a hard problem because it combines string parsing, stack management, and nested expression evaluation. Many candidates initially struggle with correctly handling parentheses and sign propagation across scopes.
Basic Calculator Python/Java solution
Python and Java solutions typically implement the stack-based scan of the expression. Both languages iterate through the characters, build numbers from digits, push state when '(' appears, and resolve sub-expressions when ')'. The logic remains O(n) time with O(n) stack space.
How to solve Basic Calculator in O(n)?
Iterate through the string while maintaining a running result, current number, and sign. When encountering '(', push the current state onto a stack and start evaluating a new sub-expression. When ')' appears, combine the computed value with the previous state. Each character is processed once, producing O(n) time complexity.
What is the best approach for Basic Calculator?
The most common solution uses a stack to evaluate the expression while scanning the string once. Each time a parenthesis is encountered, the current result and sign are pushed onto the stack and restored later. This approach runs in O(n) time and O(n) space and is widely expected in technical interviews.
Is Basic Calculator asked at Google/Amazon/Meta?
Basic Calculator is a common string parsing and stack problem that appears in interviews at large tech companies including Google, Amazon, and Meta. Variants such as Basic Calculator II and III are also frequently used to test parsing and stack fundamentals.
What data structure is used in Basic Calculator?
A stack is the primary data structure used to manage nested parentheses and restore previous evaluation states. The algorithm also uses simple variables to track the current number, running result, and sign while scanning the string.
What is the time complexity of Basic Calculator?
The optimal algorithms run in O(n) time because each character in the expression is processed exactly once. Both the stack-based and recursive approaches achieve this complexity. Space complexity is O(n) due to the stack or recursion depth for nested parentheses.

Ready to solve this problem?

Practice Basic Calculator with our built-in code editor and test cases.

Practice on FleetCode