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?- A. 12 5
- B. 18 4
- C. 19 5
- 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
- Problem: A magician reveals cards like this: show the top card, then move the next top card to the bottom; repeat. Arrange the deck so the…
- Problem: From a sorted linked list delete EVERY value that occurs more than once (keep only values that appear exactly once). python class…
- Problem: Reorder a list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place: find the middle, reverse the second half, then interleave…
- Problem: Find the area of the largest all-'1' rectangle in a binary grid by treating each row as the base of a histogram and running the…
- Problem: Does a price series contain a '132' pattern – indices i < j < k with a[i] < a[k] < a[j]? Scan from the right with a decreasing…
- Problem: Delete repeated letters so each letter appears once, and among all such results return the lexicographically smallest (a…