Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suggestion for a data structure for ranking users based on scores

I'm looking to use create and maintain the ranks in memory.

Scores associated with user ids and ranks are computed based on the scores. The following functionality should be supported.

  • Sort ranks based on scores ascending or descending. Insertion or deletion in O (log n) time.
  • Given a user id, lookup user’s rank/score along with n preceding and succeeding ranks in O(log n) time. E.g. get ranks of user 8347 with 5 preceding and succeeding ranks.
  • Retrieve n number of ranks from any offset x. E.g. get 100 ranks starting from 800

Given these requirements, are there any suggestions on which data structure suits these requirements the best?

like image 936
smahesh Avatar asked Mar 24 '11 04:03

smahesh


People also ask

What type of data structures will you use for getting top 10 students marks?

This can be done with two data structures: A hash map that maps from student name to his grade. An order statistic tree of students, where the key for comparisons is the grade.

What is rank in data structure?

The rank of an integer in-stream is “Total number of elements less than or equal to x (not including x)”. If an element is not found in the stream or is the smallest in the stream, return -1.

Which data structure is most appropriate?

An array is the simplest and most widely used data structure. Other data structures like stacks and queues are derived from arrays.


1 Answers

I think you can do this very efficiently using a combination of an order statistic tree and a hash table.

An order statistic tree is an augmented binary search tree that in addition to storing elements in sorted order, allows for lookup of elements by their index in the tree. That is, the structure supports O(lg n) insertion, deletion, and lookup of values by their key, as well as O(lg n) lookup of an element given its index. If you store the scores in this structure, you can easily insert or update new scores, as well as keeping track of the rank of each element in the tree.

In order to associate users with their scores, you could combine this structute with an auxiliary hash table mapping from user IDs to the nodes in the order statistic tree holding the score for that user. This would give you O(1) access to a player's score in addition to the O(lg n) lookup of a score's rank.

Hope this helps!

like image 195
templatetypedef Avatar answered Sep 27 '22 23:09

templatetypedef