Basic Calculator II

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Basic Calculator II

Approach

Scan the expression once, building the current number. When an operator boundary is reached, apply the previous operator: push for plus/minus, or immediately combine with stack top for multiply/divide. Sum stack at the end.

Complexity Analysis

Time
O(n)
Space
O(n)

Pattern

Stack (Operator Precedence)

Why It Works

Deferring only addition and subtraction while executing multiplication and division immediately preserves precedence without requiring a full expression tree.

Updated Feb 2026