given an array, for each element, find out the total number of elements lesser than it, which appear to the right of it

后端 未结 10 1960
傲寒
傲寒 2021-02-04 11:43

I had previously posted a question, Given an array, find out the next smaller element for each element now, i was trying to know , if there is any way to find out \"given an ar

10条回答
  •  南旧
    南旧 (楼主)
    2021-02-04 11:57

    Suppose the Array is 6,-1,5,10,12,4,1,3,7,50

    Steps

    1.We start building a BST from right end of the array.Since we are concerned with all the elements to right for any element.

    2.Suppose we have formed the partial solution tree upto the 10.

    enter image description here

    3.Now when inserting 5 we do a tree traversal and insert to the right of 4. Notice that each time we traverse to the right of any node we increment by 1 and add the no. of elements in left subtree of that node. eg:
    for 50 it is 0
    for 7 it is 0
    for 12 it is 1 right traversel + leftsubtree size of 7 = 1+3 =4
    for 10 same as above.
    for 4 it is 1+1 =2

    While building bst we can easily maintain the left subtree size for each node by simply maintaining a variable corresponding to it and incrementing it by 1 each time a node traverses to the left by it.
    Hence the Solution Average case O(nlogn).

    We can use other optimizations such as predetermining whether array is sorted in decreasing order find groups of element in decreasing order treat them as single.

提交回复
热议问题