Data Structures & AlgorithmsVery hardCAT · Codeforces Div2 B

For each index i, let d_i be (index of the nearest element to the right that is strictly greater than a[i]) minus i, or 0 if no such element exists. What is the sum of all d_i for a = [5, 3, 9, 2, 7, 1, 4]?

  1. A. 6
  2. B. 5
  3. C. 4
  4. D. 10

Correct answer: B. 5

A monotonic stack resolves a[j] the moment a strictly larger element arrives; the distance is i minus j at that moment. Elements that never get resolved contribute 0.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic