24. Basic Calculator
hardAsked at RappiEvaluate a string containing +, -, parentheses and integers — Rappi frames this as parsing a nested promo-rule expression like '(base + tip) - discount' applied to a courier payout statement.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s representing a valid arithmetic expression with +, -, (, ), spaces, and non-negative integers, evaluate the expression. Do not use eval.
Constraints
1 <= s.length <= 3 * 10^5Integers fit in 32-bit signed range
Examples
Example 1
s = "1 + 1"2Example 2
s = "(1+(4+5+2)-3)+(6+8)"23Approaches
1. Recursive parser
Recursively parse subexpressions on '(' and merge results on ')'.
- Time
- O(n)
- Space
- O(n)
// recursive descent; on '(' recurse, on ')' return; accumulate sign + number along the way.Tradeoff:
2. Stack of sign multipliers
Walk the string keeping a running result, current sign, and a stack of saved (result, sign) pairs on '(' / popped on ')'. Numbers are accumulated digit-by-digit.
- Time
- O(n)
- Space
- O(n)
function calculate(s) {
let res = 0, num = 0, sign = 1;
const st = [];
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (c >= '0' && c <= '9') num = num*10 + +c;
else if (c === '+' || c === '-') { res += sign*num; num = 0; sign = c === '+' ? 1 : -1; }
else if (c === '(') { st.push(res); st.push(sign); res = 0; sign = 1; }
else if (c === ')') { res += sign*num; num = 0; res *= st.pop(); res += st.pop(); }
}
return res + sign*num;
}Tradeoff:
Rappi-specific tips
Rappi grades for the iterative stack pattern because their promo-rules engine cannot risk recursion depth on adversarial input — they'll fail any candidate who hand-waves a stack overflow risk.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Basic Calculator and other Rappi interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →