785. Basic Calculator III
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to evaluate a mathematical expression given as a string. The expression includes non-negative integers, the four basic arithmetic operators (+, -, *, /), and parentheses for grouping. This task requires handling both operator precedence (* and / are evaluated before + and -) and nested structures defined by parentheses.
Solution
Basic Calculator III in Python
import collections
class Solution:
def calculate(self, s: str) -> int:
# Use a deque to easily pass the changing state of the string to recursive calls
q = collections.deque(s)
return self.helper(q)
def helper(self, q: collections.deque) -> int:
stack = []
num = 0
sign = '+'
while q:
char = q.popleft()
if char.isdigit():
num = num * 10 + int(char)
elif char == '(':
# Recursively call helper for the sub-expression
num = self.helper(q)
# Process the number when an operator is found, or at the end of the queue, or ')'
if (not char.isdigit() and char != ' ') or not q:
if sign == '+':
stack.append(num)
elif sign == '-':
stack.append(-num)
elif sign == '*':
stack.append(stack.pop() * num)
elif sign == '/':
# Python's `int()` truncates towards zero, which is what we need
stack.append(int(stack.pop() / num))
# Update the sign for the next number
sign = char
# Reset number for the next parsing
num = 0
if char == ')':
break # End of a sub-expression
# Sum up all numbers in the stack for the final result of this level
return sum(stack)
Basic Calculator III in Java
class Solution {
public int calculate(String s) {
Queue<Character> q = new LinkedList<>();
for (char c : s.toCharArray()) {
q.offer(c);
}
// Add a sentinel character to ensure the last number is processed
q.offer('+');
return helper(q);
}
private int helper(Queue<Character> q) {
Stack<Integer> stack = new Stack<>();
long num = 0;
char sign = '+';
while (!q.isEmpty()) {
char c = q.poll();
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
} else if (c == '(') {
// Recursively call helper for sub-expression
num = helper(q);
} else if (c != ' ') { // Process when an operator or ')' is found
if (sign == '+') {
stack.push((int) num);
} else if (sign == '-') {
stack.push((int) -num);
} else if (sign == '*') {
stack.push(stack.pop() * (int) num);
} else if (sign == '/') {
stack.push(stack.pop() / (int) num); // Java integer division truncates towards zero
}
// Update sign for the next number
sign = c;
// Reset number for the next parsing
num = 0;
if (c == ')') {
break; // End of a sub-expression
}
}
}
// Sum up all numbers in the stack for the final result of this level
int res = 0;
for (int i : stack) {
res += i;
}
return res;
}
}
Basic Calculator III in C++
class Solution {
public:
int calculate(string s) {
int i = 0;
return helper(s, i);
}
private:
int helper(const string& s, int& i) {
stack<long> st; // Use long for intermediate calculations
long num = 0;
char sign = '+';
while (i < s.length()) {
char c = s[i++];
if (isdigit(c)) {
num = num * 10 + (c - '0');
}
if (c == '(') {
num = helper(s, i);
}
// Process the number when an operator is found, or at the end of a sub-expression/string
if ((!isdigit(c) && c != ' ') || i == s.length()) {
if (sign == '+') {
st.push(num);
} else if (sign == '-') {
st.push(-num);
} else if (sign == '*') {
long top = st.top();
st.pop();
st.push(top * num);
} else if (sign == '/') {
long top = st.top();
st.pop();
st.push(top / num); // C++ integer division truncates towards zero
}
// Update the sign for the next number
sign = c;
// Reset number for the next parsing
num = 0;
if (c == ')') {
break; // End of a sub-expression
}
}
}
// Sum up all numbers in the stack for the final result of this level
long res = 0;
while (!st.empty()) {
res += st.top();
st.pop();
}
return res;
}
};
Basic Calculator III in TypeScript
function calculate(s: string): number {
let i = 0;
function helper(): number {
const stack: number[] = [];
let num = 0;
let sign = '+';
while (i < s.length) {
const char = s[i++];
// Build the current number
if (char >= '0' && char <= '9') {
num = num * 10 + (char.charCodeAt(0) - '0'.charCodeAt(0));
}
// If we see '(', recursively call helper for the sub-expression
if (char === '(') {
num = helper();
}
// Process the number when an operator is found, or at the end of a sub-expression/string
if (((char < '0' || char > '9') && char !== ' ') || i === s.length) {
if (sign === '+') {
stack.push(num);
} else if (sign === '-') {
stack.push(-num);
} else if (sign === '*') {
stack.push(stack.pop()! * num);
} else if (sign === '/') {
const top = stack.pop()!;
// Math.trunc provides truncation towards zero, e.g., Math.trunc(-1.5) is -1
stack.push(Math.trunc(top / num));
}
// Update sign for the next number
sign = char;
// Reset number for the next parsing
num = 0;
if (char === ')') {
break; // End of a sub-expression
}
}
}
// Sum up all numbers in the stack for the final result of this level
return stack.reduce((acc, val) => acc + val, 0);
}
return helper();
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.