Advertisement

Basic Calculator - LeetCode 224 Solution

Basic Calculator - Complete Solution Guide

Basic Calculator is LeetCode problem 224, a Hard level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

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 * 10 5 s consists of digits, '+' , '-' , '(' , ')' , and ' ' . s re

Detailed Explanation

The problem asks us to implement a basic calculator that can evaluate a given string expression. The expression consists of digits, '+', '-', '(', ')', and spaces. The calculator should return the integer result of the evaluation. We are not allowed to use built-in functions like `eval()` to directly evaluate the string.

Solution Approach

The provided solutions use a stack to keep track of intermediate results and signs when encountering parentheses. The algorithm iterates through the string character by character. It maintains a current number, result, and sign. When a digit is encountered, it's appended to the current number. When an operator ('+' or '-') is encountered, the current number (multiplied by the current sign) is added to the result, and the number and sign are reset. When an opening parenthesis is encountered, the current result and sign are pushed onto the stack, and the result and sign are reset. When a closing parenthesis is encountered, the current number (multiplied by the current sign) is added to the result, the previous sign and result are popped from the stack, and the result is updated to reflect the value of the expression within the parentheses.

Step-by-Step Algorithm

  1. Step 1: Initialize a stack, result, sign (to 1), and num (to 0).
  2. Step 2: Iterate through the input string character by character.
  3. Step 3: If the character is a digit, update the current number: `num = num * 10 + int(char)`.
  4. Step 4: If the character is '+', update the result: `result += sign * num`, reset `num = 0`, and set `sign = 1`.
  5. Step 5: If the character is '-', update the result: `result += sign * num`, reset `num = 0`, and set `sign = -1`.
  6. Step 6: If the character is '(', push the current `result` and `sign` onto the stack, reset `result = 0`, and set `sign = 1`.
  7. Step 7: If the character is ')', update the result: `result += sign * num`, reset `num = 0`. Pop the previous `sign` and `result` from the stack. Update the `result` to be `prev_result + prev_sign * result`.
  8. Step 8: After iterating through the entire string, if `num` is not 0, update the `result`: `result += sign * num`.
  9. Step 9: Return the final `result`.

Key Insights

  • Insight 1: The use of a stack is crucial for handling the nested parentheses. The stack stores intermediate results and signs when encountering an opening parenthesis and retrieves them when encountering a closing parenthesis.
  • Insight 2: We need to keep track of the current sign (positive or negative) to handle subtractions and additions correctly. The sign changes when encountering the '-' operator and needs to be applied to subsequent numbers until another operator is encountered.
  • Insight 3: The problem constraints state that '+' is not a unary operator but '-' can be. This allows us to handle cases where the number is preceded by a '-'. The sign needs to be correctly managed to reflect this unary operation.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(n)

Topics

This problem involves: Math, String, Stack, Recursion.

Companies

Asked at: Anduril, ByteDance, Citadel, Coupang, DE Shaw, DoorDash, Oracle, Palo Alto Networks, Ripple, Rokt, Snowflake, Tesla.