Data Structures & AlgorithmsHardProduct Company SDE · stack round

Problem: Sum the values of the next greater element of each position in [2, 1, 4, 3], where a position with no greater element contributes 0. Run the code.

Problem: Sum the values of the next greater element of each position in [2, 1, 4, 3], where a position with no greater element contributes 0. Run the code.
a = [2, 1, 4, 3]
res = [0] * len(a)
st = []
for i, x in enumerate(a):
    while st and a[st[-1]] < x:
        res[st.pop()] = x
    st.append(i)
print(sum(res))
What is printed?
  1. A. 8
  2. B. 7
  3. C. 4
  4. D. 9

Correct answer: A. 8

The next greater values are 4 for 2, 4 for 1 and 0 for the two larger elements (4 and 3 have none), totalling 8. Counting the untouched positions as -1 changes the sum.

More Coding Interview Problems questions

Exams that ask this topic