I have a sequence. And now for each element in this sequence I would like to know how many subsequent elements are larger. Or, in other words, I have a sequence $a_1, \ldots, a_n$, and for each $1\leq i\leq n$ I would like to compute $|\lbrace j|j>i\wedge a_j > a_i\rbrace|$.

My idea: Implement an AVL tree, put elements from this sequence to this AVL tree from the last one to the first one. Before putting each element obtain the amount of larger elements the tree already contains. I can implement an AVL tree that would allow such operations.

But alas, I do have to implement such an AVL tree, since unfortunately the standard C++ std::set doesn't allow obtaining the distance between two iterators in logarithmic time.

Now I need this to solve a task from one of the former exams on algorithms and data structures. These exams usually contain two tasks, a "simpler" one and a "harder" one. And this is the "simpler" one. Now I doubt that a "simpler" task would require implementing an AVL tree. A "harder" task might; but a "simpler" one, doubtfully. Therefore, I would say, there should be a less laborious way to solve this task.

Is there any simpler way to compute what I need to compute?

  • 1
    $\begingroup$ It may help to sort the sequence and look at the difference in indexes of the same element in the sorted sequence vs the original sequence. $\endgroup$
    – Discrete lizard
    Commented Jan 17, 2018 at 11:00
  • $\begingroup$ A faster way than to tally values from $a_n$ to $a_1$ gave a faster way to order the $a_i$. $\endgroup$
    – greybeard
    Commented Jul 26, 2022 at 8:13
  • $\begingroup$ You did not use the magical work "efficiently". So brute force is the simplest. $\endgroup$
    – user16034
    Commented Jul 26, 2022 at 8:24

1 Answer 1


You can use any balanced binary search tree data structure (doesn't have to be AVL tree). Some such data structures are easier to implement (maybe a AA tree, left-leaning red-black tree, or splay tree?). If you don't care about worst-case running time, it doesn't need to be balanced. One pragmatic solution might be to use skip lists.

Are you sure the exam required students to implement their solution? In my experience, exams in the algorithms and data structure courses I'm familiar with rarely require implementing the solution -- it is enough to describe the solution clearly. A solution based on augmenting an AVL tree can be described in a fairly simple way: you say "take a AVL tree, and modify it in such-and-such a way", and that doesn't require re-describing all the details of how AVL trees work. Only you know what the typical expectations are for the kind of exam you are looking at.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.