Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Evaluate a reverse-Polish expression. The specification says division must truncate toward zero (as in C or Java).
Problem: Evaluate a reverse-Polish expression. The specification says division must truncate toward zero (as in C or Java).
def rpn(tokens):
st = []
for t in tokens:
if t in "+-*/":
b, a = st.pop(), st.pop()
st.append(a + b if t == '+' else a - b if t == '-' else a * b if t == '*' else a // b)
else:
st.append(int(t))
return st[0]
print(rpn(["7", "-3", "/", "2", "*"]))What is printed?- A. -4
- B. -6
- C. -5
- D. -3
Correct answer: B. -6
Python's // floors, so 7 // −3 = −3 (not −2) and the result is −3 × 2 = −6. Truncation toward zero would give −2 × 2 = −4, so this code violates the spec for mixed signs; int(a / b) fixes it.
More Coding Interview Problems questions
- Problem: Sum the minimum of every contiguous subarray using a monotonic stack (previous-less and next-less-or-equal boundaries). python…
- Problem: Count the distinct non-empty substrings of a short string. python s = "ababa" print(len({s[i:j] for i in range(len(s)) for j in…
- Problem: Compute the KMP prefix function (pi[i] = length of the longest proper prefix of s[0..i] that is also its suffix). python def…
- Problem: Compute the Z-array (z[i] = length of the longest substring starting at i that matches a prefix of s; z[0] is set to 0). python…
- Problem: Floyd's cycle detection on a linked list whose tail points back into the middle. Report the value where slow and fast first meet…
- Problem: Rob houses arranged as a tree (node 0 is the root; parent[i] gives each node's parent). Directly linked houses cannot both be…