Find relative rank of each element in array | Function to find relative rank for each element in the array A [ ] ; Create Rank Array ; Stack to store numbers in non - decreasing order from right ; Push last element in stack ; Iterate from second last element to first element ; If current element is less than the top of stack and append A [ i ] in stack ; Rank is stack size - 1 for current element ; Pop elements from stack till current element is greater than the top ; Push current element in Stack ; Rank is stack size - 1 ; Print rank of all elements ; Driver Code ; Given array A [ ] ; Function call
def findRank ( A , N ) : NEW_LINE INDENT rank = [ 0 ] * N NEW_LINE s = [ ] NEW_LINE s . append ( A [ N - 1 ] ) NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ i ] < s [ - 1 ] ) : NEW_LINE INDENT s . append ( A [ i ] ) NEW_LINE rank [ i ] = len ( s ) - 1 NEW_LINE DEDENT else : NEW_LINE INDENT while ( len ( s ) > 0 and A [ i ] >= s [ - 1 ] ) : NEW_LINE INDENT del s [ - 1 ] NEW_LINE DEDENT s . append ( A [ i ] ) NEW_LINE rank [ i ] = len ( s ) - 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( rank [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 5 , 4 ] NEW_LINE N = len ( A ) NEW_LINE findRank ( A , N ) NEW_LINE DEDENT