Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Evaluate an expression with +, −, parentheses and non-negative integers, using a stack of signs.
Problem: Evaluate an expression with +, −, parentheses and non-negative integers, using a stack of signs.
def calc(s):
res, num, sign, st = 0, 0, 1, []
for c in s:
if c.isdigit(): num = num * 10 + int(c)
elif c in "+-":
res += sign * num; num = 0; sign = 1 if c == '+' else -1
elif c == '(':
st.append((res, sign)); res, sign = 0, 1
elif c == ')':
res += sign * num; num = 0
pr, ps = st.pop(); res = pr + ps * res
return res + sign * num
print(calc("1-(2-(3-4))+5"))What is printed?- A. 1
- B. 5
- C. 11
- D. 3
Correct answer: D. 3
Inside out: 3 − 4 = −1, then 2 − (−1) = 3, then 1 − 3 + 5 = 3. Saving (result, sign) at each '(' lets the closing ')' apply the sign that preceded the bracket to the whole inner value.
More Coding Interview Problems questions
- Problem: Remove duplicate letters so that each letter appears once and the result is the lexicographically smallest possible subsequence…
- Problem: Report the running median of a stream using a max-heap (lower half) and a min-heap (upper half). python import heapq def…
- Which statement about selecting the k-th smallest of n unsorted numbers is correct?
- Problem: Find the smallest divisor d such that Σ ceil(a[i] / d) ≤ threshold. python def smallestdiv(a, t): lo, hi = 1, max(a) while lo <…
- Problem: Buses i take time[i] minutes per trip and run independently and repeatedly. Find the minimum time for all buses together to…
- Problem: Use bisect to count how many readings lie in the closed range [2, 7]. python from bisect import bisectleft, bisectright a = [1…