Data Structures & AlgorithmsHardProduct company OA

Problem: Evaluate an expression of non-negative integers with + − / (no brackets, / truncates toward zero) in one pass with a stack.

Problem: Evaluate an expression of non-negative integers with + − * / (no brackets, / truncates toward zero) in one pass with a stack.
def calc(s):
    st, num, op = [], 0, "+"
    for c in s + "+":
        if c.isdigit():
            num = num * 10 + int(c)
        elif c in "+-*/":
            if op == "+": st.append(num)
            elif op == "-": st.append(-num)
            elif op == "*": st.append(st.pop() * num)
            else: st.append(int(st.pop() / num))
            op, num = c, 0
    return sum(st)
print(calc("14-3*4/5+2*3"), calc("7-10/4"))
What is printed?
  1. A. 12 5
  2. B. 18 4
  3. C. 19 5
  4. D. 18 5

Correct answer: D. 18 5

+ and − push signed terms; * and / immediately combine with the last term, giving them higher precedence. 14 − 3·4/5 + 2·3: terms 14, −(12/5 → 2), 6 → 18. For 7 − 10/4 the term on the stack is −10, and int(−10/4) = int(−2.5) = −2 → 5. Using floor division // would give −3 and 4, and evaluating left to right ((14−3)·4/5…) ignores precedence. O(n).

More Coding Interview Problems questions

Exams that ask this topic