Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: Evaluate an expression in Reverse Polish notation; division truncates toward zero.
Problem: Evaluate an expression in Reverse Polish notation; division truncates toward zero.
def rpn(tokens):
st = []
for t in tokens:
if t in "+-*/":
b, a = st.pop(), st.pop()
if t == '+': st.append(a + b)
elif t == '-': st.append(a - b)
elif t == '*': st.append(a * b)
else: st.append(int(a / b))
else:
st.append(int(t))
return st[0]
print(rpn(["4", "13", "5", "/", "+"]), rpn(["7", "-3", "/"]), 7 // -3)What is printed?- A. 6 -3 -3
- B. 6 -2 -2
- C. 5 -2 -3
- D. 6 -2 -3
Correct answer: D. 6 -2 -3
13 / 5 = 2, then 4 + 2 = 6. For 7 / −3 the problem wants truncation toward zero (−2), as in C/Java; Python's // floors to −3, which is why int(a / b) is used. The second popped value is the left operand. O(n).
More Coding Interview Problems questions
- Problem: Simulate asteroids on a line: positive moves right, negative left; on collision the smaller explodes, equal sizes both explode…
- Problem: Remove k digits from a number string to make the smallest possible number (no leading zeros in the result, "0" if empty). python…
- Problem: Design a stack that returns its minimum in O(1). The implementation below stores pairs. python st = [] def push(x): st.append((x…
- Problem: Return the first index whose value is ≥ x in a sorted array (n if none). cpp int lowerBound(vector<int>& a, int x) { int lo = 0…
- Problem: Count how many times a value occurs in a sorted array in O(log n). python from bisect import bisectleft, bisectright a = [2, 4…
- Problem: Search a target in a sorted array of distinct values that has been rotated at an unknown pivot. python def search(a, t): lo, hi =…