Data Structures & AlgorithmsModerateAmazon · Microsoft OA
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.
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.
def spans(p):
st, out = [], []
for i, x in enumerate(p):
while st and p[st[-1]] <= x: st.pop()
out.append(i + 1 if not st else i - st[-1])
st.append(i)
return out
print(spans([31, 27, 14, 21, 30, 22]))What is printed?- A. [1, 1, 1, 2, 4, 1]
- B. [1, 1, 1, 2, 3, 1]
- C. [1, 1, 1, 2, 4, 2]
- D. [1, 2, 3, 4, 5, 6]
Correct answer: A. [1, 1, 1, 2, 4, 1]
The stack keeps indices of a decreasing run of prices. On 30, the prices 21, 14 and 27 are all ≤ 30 and popped, leaving 31 at index 0, so the span is 4 − 0 = 4. On 22, the previous price 30 is higher, so the span is 1.
More Coding Interview Problems questions
- 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…
- Which statement about selecting the k-th smallest of n unsorted numbers is correct?