Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: For each day, how many days until a strictly warmer day (0 if none)?
Problem: For each day, how many days until a strictly warmer day (0 if none)?
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, 38, 30, 36, 35, 40, 28]))What is printed?- A. [1, 4, 1, 2, 1, 0, 1]
- B. [1, 3, 1, 2, 1, 0, 0]
- C. [1, 4, 2, 2, 1, 0, 0]
- D. [1, 4, 1, 2, 1, 0, 0]
Correct answer: D. [1, 4, 1, 2, 1, 0, 0]
The stack holds days still waiting for a warmer one. 38 waits until 40 at index 5 (4 days); 36 waits 2 days for 40; the last day 28 never finds a warmer day, so it stays 0.
More Coding Interview Problems questions
- Problem: The span of a stock on a day is the number of consecutive days up to and including it with price ≤ that day's price. python def…
- Problem: Asteroids move along a line: positive = right, negative = left, |value| = size. When two meet, the smaller explodes; equal sizes…
- Problem: Decode a string where k[s] means s repeated k times (brackets can nest). python def decode(s): st, cur, k = [], "", 0 for c in s…
- Problem: Evaluate an expression with +, −, parentheses and non-negative integers, using a stack of signs. python def calc(s): res, num…
- 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…