Data Structures & AlgorithmsHardTCS NQT Digital · Product Company SDE

Problem: For the array [4, 1, 5, 2, 6, 3, 7], compute, for each index i, the distance to the next strictly greater element to its right (0 if none exists, and the distance is index difference). What is the sum of these distances?

  1. A. 3
  2. B. 24
  3. C. 10
  4. D. 9

Correct answer: D. 9

A monotonic stack gives next-greater distances 2, 1, 2, 1, 2, 1, 0, summing to 9. Looking left for the previous greater element gives 3, adding the target indices instead of distances gives 24, and charging n − i for the last element instead of 0 gives 10.

More Coding Interview Problems questions

Exams that ask this topic