Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Evaluate an expression with +, −, parentheses and non-negative integers, using a stack of signs.

Problem: Evaluate an expression with +, −, parentheses and non-negative integers, using a stack of signs.
def calc(s):
    res, num, sign, st = 0, 0, 1, []
    for c in s:
        if c.isdigit(): num = num * 10 + int(c)
        elif c in "+-":
            res += sign * num; num = 0; sign = 1 if c == '+' else -1
        elif c == '(':
            st.append((res, sign)); res, sign = 0, 1
        elif c == ')':
            res += sign * num; num = 0
            pr, ps = st.pop(); res = pr + ps * res
    return res + sign * num
print(calc("1-(2-(3-4))+5"))
What is printed?
  1. A. 1
  2. B. 5
  3. C. 11
  4. D. 3

Correct answer: D. 3

Inside out: 3 − 4 = −1, then 2 − (−1) = 3, then 1 − 3 + 5 = 3. Saving (result, sign) at each '(' lets the closing ')' apply the sign that preceded the bracket to the whole inner value.

More Coding Interview Problems questions

Exams that ask this topic