AlgoMaster Logo

Basic Calculator II

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Two Stacks

Intuition:

The problem requires us to evaluate a string containing a mathematical expression with +-*, and /. A straightforward approach is to use two stacks: one for numbers and another for operators. This is similar to the standard method used for evaluating expressions.

Steps:

  1. Use two stacks: one for operands (numbers) and one for operators.
  2. Traverse each character in the string:
    • If it's a digit, build the number.
    • If it's an operator, push the current number to the operands stack, then push the operator to the operators stack.
    • Evaluate whenever necessary (* and / have higher precedence).
  3. Pop remaining operators and operands to calculate the result using a simple post-fix evaluation.
  4. Return the result.

Code:

2. One Stack

Intuition:

By recognizing the fact that * and / operations are executed immediately and have higher precedence, we can simplify our approach by using only one stack. We can optimize by directly evaluating the immediate * and / results on the numbers residing in the stack.

Steps:

  1. Initialize one stack to store evaluated values.
  2. Traverse the string similarly and calculate results on the fly based on operator priorities.
  3. Append intermediate results computed by * and / into the stack.
  4. Sum up the stack to get the final result.

Code:

3. In-Place Calculation Using Single Pass and Single Stack

Intuition:

We can make this more efficient by minimizing stack use to only necessary intermediate results. We can modify the processed result in place using a single pass through the string. By evaluating high-priority operations as soon as possible, only results of addition/subtraction need to be stored.

Steps:

  1. Use a single stack to store previous evaluated results and only nums needed for adjusting the result from unfinished operations when needed.
  2. Track running total adjusted with prior operations.
  3. Evaluate high-precedence operations (*/) immediately and push intermediate results into the stack.
  4. Perform addition and subtraction on accumulated results from the stack at the end.

Code: