Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Evaluate a basic calculator expression with +, −, parentheses and spaces.

Problem: Evaluate a basic calculator expression with +, −, parentheses and spaces.
def calc(s):
    res, num, sign, st = 0, 0, 1, []
    for ch in s:
        if ch.isdigit(): num = num * 10 + int(ch)
        elif ch in '+-':
            res += sign * num; num = 0; sign = 1 if ch == '+' else -1
        elif ch == '(':
            st.append((res, sign)); res, sign = 0, 1
        elif ch == ')':
            res += sign * num; num = 0
            prev, sg = st.pop(); res = prev + sg * res
    return res + sign * num
print(calc("(1+(4+5+2)-3)+(6+8)"), calc("2-(5-6)"), calc("- (3 + (4 - 10))"))
What is printed?
  1. A. 23 -3 3
  2. B. 21 3 3
  3. C. 23 3 -3
  4. D. 23 3 3

Correct answer: D. 23 3 3

A stack stores the result and sign before each '('; at ')' the inner result is combined with them. 2 − (5 − 6) = 2 + 1 = 3, and −(3 + (−6)) = 3; ignoring the sign saved before '(' gives −3. Multi-digit numbers are built with num·10 + digit. O(n).

More Coding Interview Problems questions

Exams that ask this topic