Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: For each element, the nearest smaller value to its LEFT (−1 if none), with a monotonic stack.
Problem: For each element, the nearest smaller value to its LEFT (−1 if none), with a monotonic stack.
def left_smaller(a):
st, out = [], []
for x in a:
while st and st[-1] >= x: st.pop()
out.append(st[-1] if st else -1)
st.append(x)
return out
print(left_smaller([4, 5, 2, 10, 8, 2, 9]))What is printed?- A. [-1, 4, 2, 2, 2, 2, 2]
- B. [-1, 4, 4, 2, 10, 2, 8]
- C. [-1, -1, -1, 2, 2, 2, 2]
- D. [-1, 4, -1, 2, 2, -1, 2]
Correct answer: D. [-1, 4, -1, 2, 2, -1, 2]
The stack keeps a strictly increasing sequence of candidates. For 8 the stack is [2, 10], 10 is popped and 2 remains. For the second 2, the earlier 2 is popped too (≥ is used), so the answer is −1: equal values do not count as smaller. 9 then sees 2.
More Coding Interview Problems questions
- Problem: Report the first negative number in every window of size k (0 if none), using a queue of negative indices. python from…
- Problem: Reorder a linked list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place (find middle, reverse second half, merge). python…
- Problem: From a sorted linked list, delete EVERY value that appears more than once (keep only distinct values). python class N: def…
- Problem: Sum all LEFT leaves of a binary tree (leaves that are the left child of their parent). python class T: def init(s, v): s.v, s.l…
- Problem: List every root-to-leaf path whose values sum to the target. python class T: def init(s, v): s.v, s.l, s.r = v, None, None def…
- Problem: Count the BST keys within [lo, hi], pruning subtrees that cannot contain answers. python class T: def init(s, v): s.v, s.l, s.r =…