TryAlgo

Rank in suffix

Given an integer table t1,…,tn compute for every position 1≤i≤n the rank of t[i] among the suffix t[i,…,n] that is the number of j≥i such that t[j]≤t[i].

A solution in time \(O(n \log n)\)

First suppose that all values in t are between 0 and n-1. This can be done by creating a sorted copy of t, say s, and compute a reverse lookup table \(s^{-1}\), that maps every value from \(t\) to the index of the first occurrence in \(s\).

Then the trick is to process the table from the end to the beginning. Maintain a segment tree, which is a data structure encoding a table A of size n (initially all zero), allowing the following operations to run in time \(O(\log n)\):

The algorithm

Notes

In the above mentioned problem puchi and luggage the specification excluded t[i] from the suffix in which the rank is to be found. Hence all answers have be produced decremented by 1. This can be obtained by swapping the two segment tree instructions increment and prefix sum in the above algorithm.