I know that this problem can be solved using modified merge sort and I have coded same. Now I want to solve this problem using Segment Tree. Basically, if we traverse from right to left array then we have to count the "how many values are greater than current value". How this thing can be achieved by Segment Tree?
What type of information we have to store on Segment Tree Node?
Please provide code if possible.
Let me explain step by step with an example:
First, sort the array in descending order as {value, index} pair.
Iterating from left to right, for each element
arr[i]
-Query for each element's
index
(query for range[0, arr[i].index]
to get the greater numbers count on left side) and put the query result on correspondingindex
of output array.After each query, increment the corresponding segment tree node which covers that
index
.This way, we are ensuring to get only greater numbers count from
0
toindex - 1
as values only greater thanarr[i]
have been inserted so far.Below C++ implementation will make more sense.
This is easy one but not pretty "obvious" as other typical segment tree problem. Simulating with pen and paper with an arbitrary input will help.
There are other
O(nlogn)
approaches with BST, Fenwick tree and merge sort.