Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Compute the stock span: for each day, the number of consecutive days up to today with price ≤ today's price.
Problem: Compute the stock span: for each day, the number of consecutive days up to today with price ≤ today'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([100, 80, 60, 70, 60, 75, 85]))What is printed?- A. [1, 1, 1, 2, 1, 3, 6]
- B. [1, 1, 1, 2, 1, 4, 5]
- C. [1, 1, 1, 2, 1, 4, 6]
- D. [1, 2, 3, 4, 5, 6, 7]
Correct answer: C. [1, 1, 1, 2, 1, 4, 6]
Pop all previous days with price ≤ today; the remaining top is the previous greater day, and the span is the distance to it. 75 covers 60, 70, 60, 75 → 4; 85 covers back to just after 100 → 6. O(n) amortised.
More Coding Interview Problems questions
- 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))…
- Problem: Count the distinct values taken by the bitwise OR of all contiguous subarrays. python def distinctor(a): res, cur = set(), set()…
- Problem: Compute the maximum XOR of any two numbers using a greedy prefix-set approach bit by bit. python def maxxor(a): ans = mask = 0…
- Problem: Implement atoi: skip leading spaces, read an optional sign and digits, stop at the first non-digit, clamp to 32-bit range. python…