Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Evaluate a basic calculator expression with +, −, parentheses and spaces.
Problem: Evaluate a basic calculator expression with +, −, parentheses and spaces.
def calc(s):
res, num, sign, st = 0, 0, 1, []
for ch in s:
if ch.isdigit(): num = num * 10 + int(ch)
elif ch in '+-':
res += sign * num; num = 0; sign = 1 if ch == '+' else -1
elif ch == '(':
st.append((res, sign)); res, sign = 0, 1
elif ch == ')':
res += sign * num; num = 0
prev, sg = st.pop(); res = prev + sg * res
return res + sign * num
print(calc("(1+(4+5+2)-3)+(6+8)"), calc("2-(5-6)"), calc("- (3 + (4 - 10))"))What is printed?- A. 23 -3 3
- B. 21 3 3
- C. 23 3 -3
- D. 23 3 3
Correct answer: D. 23 3 3
A stack stores the result and sign before each '('; at ')' the inner result is combined with them. 2 − (5 − 6) = 2 + 1 = 3, and −(3 + (−6)) = 3; ignoring the sign saved before '(' gives −3. Multi-digit numbers are built with num·10 + digit. O(n).
More Coding Interview Problems questions
- Problem: Decode a string like 3[a2[c]] where k[...] repeats the bracket content k times. python def decode(s): st, cur, k = [], '', 0 for…
- Problem: For each element, find the next greater element in a circular array (−1 if none). python def ngecircular(a): n = len(a); res =…
- Problem: Compute the stock span: for each day, the number of consecutive days up to today with price ≤ today's price. python def spans(p)…
- Problem: Return the k most frequent words, ties broken alphabetically. python from collections import Counter def topk(words, k): c =…
- Problem: Check whether two strings are isomorphic (characters map one-to-one consistently). python def iso(s, t): return len(set(s)) ==…
- Problem: Find the minimum number of swaps to sort an array of distinct values. python def minswaps(a): order = sorted(range(len(a))…