</>

224. Basic Calculator

Hard
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Stack
Time
—
Space
—

Standard Solution (C++)

SummaryGiven a string representing an arithmetic expression with integers, `+`, `-`, spaces, and parentheses, evaluate it and return the integer result. No multiplication or division is present, but parentheses may be arbitrarily nested.

Approach
  • Track a running result, a pending number, and the current sign (+1 or -1) for the upcoming term.
  • When a ( is encountered, push the current result and sign onto the stack, then reset them to start fresh inside the sub-expression.
  • When a ) is encountered, finalize the sub-expression result, then pop the saved sign and outer result to re-integrate the parenthesized value: outer_result + saved_sign * sub_result.
  • A single linear scan suffices because each character is processed exactly once, and the stack depth is bounded by parenthesis nesting depth.
#include <string>
#include <stack>
using namespace std;

class Solution {
public:
    int calculate(string s) {
        stack<int> stk;  // alternates: saved_result, saved_sign, saved_result, saved_sign...
        int result = 0;
        int number = 0;
        int sign   = 1;  // +1 or -1

        for (char c : s) {
            if (isdigit(c)) {
                // accumulate multi-digit numbers
                number = number * 10 + (c - '0');
            } else if (c == '+' || c == '-') {
                // commit the pending number, reset for next term
                result += sign * number;
                number  = 0;
                sign    = (c == '+') ? 1 : -1;
            } else if (c == '(') {
                // save context and start a fresh sub-expression
                stk.push(result);
                stk.push(sign);
                result = 0;
                sign   = 1;
            } else if (c == ')') {
                // finalize sub-expression
                result += sign * number;
                number  = 0;
                // restore: sub_result is scaled by saved sign, then added to outer result
                int saved_sign   = stk.top(); stk.pop();
                int saved_result = stk.top(); stk.pop();
                result = saved_result + saved_sign * result;
            }
            // spaces are silently skipped
        }

        // commit any trailing number not yet folded in
        result += sign * number;
        return result;
    }
};
Time O(n) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <string>
#include <stack>
using namespace std;

class Solution {
public:
    int calculate(string s) {
        long long res=0;
        long long cur=0;
        int sign=1;
        stack<long long> st;

        for(const char c: s){
            if(isdigit(c)){
                cur=cur*10+(c-'0');
            }
            else if(c=='+'){
                res+=cur*sign;
                cur=0;
                sign=1;
            }
            else if(c=='-'){
                res+=cur*sign;
                cur=0;
                sign=-1;
            }
            else if(c=='('){
                st.push(res);
                st.push(sign);
                res=0;
                sign=1;
            }
            else if(c==')'){
                res+=cur*sign;
                cur=0;

                long long prev_sign=st.top();
                st.pop();
                long long prev_res=st.top();
                st.pop();

                res=prev_res+prev_sign*res;
            }
        }
        res+=sign*cur;
        return res;
    }
};

// Time: O(N)
// Space: O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern