Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: For each day's temperature, find how many days you must wait for a warmer day (0 if never).
Problem: For each day's temperature, find how many days you must wait for a warmer day (0 if never).
def wait(t):
res, st = [0] * len(t), []
for i, x in enumerate(t):
while st and t[st[-1]] < x:
j = st.pop()
res[j] = i - j
st.append(i)
return res
print(wait([30, 32, 31, 31, 35, 29, 30]))What is printed?- A. [1, 3, 1, 1, 0, 1, 0]
- B. [1, 2, 2, 1, 0, 1, 0]
- C. [1, 3, 2, 1, 0, 1, 0]
- D. [1, 3, 2, 1, 0, 0, 0]
Correct answer: C. [1, 3, 2, 1, 0, 1, 0]
A stack keeps indices with non-increasing temperatures; a warmer day pops them and fills their wait. 32 waits until 35 (3 days); both 31s also wait for 35 (2 and 1 days) because equal is not warmer. 29 waits 1 day for 30. Each index is pushed and popped once: O(n).
More Coding Interview Problems questions
- Problem: Find the largest rectangle that fits under a histogram of bar heights. python def largest(h): st, best = [], 0 for i, x in…
- Problem: Evaluate an expression in Reverse Polish notation; division truncates toward zero. python def rpn(tokens): st = [] for t in…
- 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…