From 70984609e9df26d492878fd90babf9bd85417b1f Mon Sep 17 00:00:00 2001 From: "Gumparthy Pavan Kumar[pk]" Date: Sun, 27 Jul 2025 10:49:03 +0530 Subject: [PATCH] fix: operator precedence for leetcode 227 [basic calculator ii] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. What is now different from before? > The implementation now reverses the numbers and operators stacks before applying + and - operators.This ensures that + and - are evaluated in left-to-right order, which matches the expected behavior of the expression (i.e., left-associative evaluation). Previously, operators were applied in reverse order, leading to incorrect results like 1-1+1 → -1 instead of 1. 2. What is the reason for the change? > + and - are left-associative operators with the same precedence, and must be processed in the order they appear. 3. Anything to watch out for? > Space complexity increases slightly due to the temporary numRev and opRev stacks, but remains O(n). --- c++/basic-calculator-ii.md | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/c++/basic-calculator-ii.md b/c++/basic-calculator-ii.md index 0c76c1d..e6b978f 100644 --- a/c++/basic-calculator-ii.md +++ b/c++/basic-calculator-ii.md @@ -60,18 +60,31 @@ int calculate(std::string s) { } } - // Now process remaining operators for addition or subtraction - int result = numbers.top(); - numbers.pop(); - while (!numbers.empty()) { - char op = operators.top(); - operators.pop(); - int num = numbers.top(); + // Reverse the stacks to maintain left-to-right order + std::stack numbersRev; + std::stack operatorsRev; + while(!numbers.empty()) { + numbersRev.push(numbers.top()); numbers.pop(); + } + + while(!operators.empty()) { + operatorsRev.push(operators.top()); + operators.pop(); + } + + // Now process remaining operators for addition or subtraction + int result = numbersRev.top(); + numbersRev.pop(); + while (!numbersRev.empty()) { + char op = operatorsRev.top(); + operatorsRev.pop(); + int num = numbersRev.top(); + numbersRev.pop(); if (op == '+') { result += num; } else if (op == '-') { - result = num - result; + result -= num; } } @@ -87,7 +100,7 @@ int main() { #### Complexity: - **Time Complexity:** O(n), where n is the length of the string, since we are iterating once through the input. -- **Space Complexity:** O(n), due to the supplementary space used by two stacks. +- **Space Complexity:** O(n), due to the supplementary space used by four stacks. ---