Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Evaluate an expression with +, −, , / (integer division truncating toward zero) and no parentheses, using a stack.
Problem: Evaluate an expression with +, −, *, / (integer division truncating toward zero) and no parentheses, using a stack.
def calc(s):
st, num, op = [], 0, '+'
for i, c in enumerate(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("3+5/2*4-6/4"), calc("14-3*2/4"))What is printed?- A. 11 11
- B. 10 13
- C. 10 12
- D. 4 13
Correct answer: B. 10 13
* and / are applied immediately to the top of the stack, + and − only push signed terms. 3 + (5/2 = 2)·4 − (6/4 = 1) = 3 + 8 − 1 = 10; 14 − (3·2 = 6)/4 → 14 − 1 = 13, since −6/4 truncates to −1 (floor division would give −2 and 12).
More Coding Interview Problems questions
- Problem: Find every start index in s of a substring that is a concatenation of all the given words (each exactly once, any order; all…
- Problem: Find the shortest contiguous substring of S that contains T as a SUBSEQUENCE (leftmost on ties). Scan forward to complete T, then…
- Problem: Find the longest substring that occurs at least twice (occurrences may overlap): binary search on the length with a set of…
- Problem: Count how many words are subsequences of s, by bucketing words by the next character they are waiting for. python from…
- Problem: Roads are one-way (a → b). Reorient the fewest roads so every city can reach city 0 (the roads form a tree). python def…
- Problem: A grid has exactly two islands (1s). Find the minimum number of 0s to flip to connect them (BFS outward from the first island)…