Data Structures & AlgorithmsHardGATE CS · Codeforces Div2 C

For each index i of [4, 2, 5, 3, 1, 6], let dist(i) be the distance to the next index j > i with a[j] < a[i] (dist = n − i if no such index exists, where n is the length). What is the sum of dist(i) over all i?

  1. A. 12
  2. B. 9
  3. C. 7
  4. D. 21

Correct answer: B. 9

Monotonic stack (increasing values): when a smaller value arrives, pop each larger index and set its distance to the current index minus its own. Indices left on the stack keep distance n − i. Using the previous smaller element changes the distances.

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

Exams that ask this topic