Data Structures & AlgorithmsHardProduct Company SDE · stack round

Problem: For each index of a = [4, 5, 2, 10, 8], find the index of the nearest element to its left that is strictly smaller (or -1). Run the monotone-stack code.

Problem: For each index of a = [4, 5, 2, 10, 8], find the index of the nearest element to its left that is strictly smaller (or -1). Run the monotone-stack code.
a = [4, 5, 2, 10, 8]
st = []
res = []
for i, x in enumerate(a):
    while st and a[st[-1]] >= x:
        st.pop()
    res.append(st[-1] if st else -1)
    st.append(i)
print(res)
What is printed?
  1. A. [-1, 0, -1, 2, 4]
  2. B. [-1, 0, -1, 2, 2]
  3. C. [-1, -1, -1, 2, 2]
  4. D. [-1, 0, 1, 2, 3]

Correct answer: B. [-1, 0, -1, 2, 2]

For 10 at index 3 the nearest smaller value is 2 at index 2, and for 8 it is again index 2. Using the nearest greater element instead gives a different list.

More Coding Interview Problems questions

Exams that ask this topic