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?
  1. A. [-1, 4, 2, 2, 2, 2, 2]
  2. B. [-1, 4, 4, 2, 10, 2, 8]
  3. C. [-1, -1, -1, 2, 2, 2, 2]
  4. 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

Exams that ask this topic