What is the best data structure to move the nth element forward?


so I need to move n-th element from beginning and move it to the front (and shifting 0,..,n-1 items to the right). What would be best data structure to use and how should I go about it?

I already thinking about skiplist, but don't know how to get O(log n) for access via index. Are there any better things (trees or something) I should use?

Thanks in advance..

Language: C++

Disclaimer: Yes, this is homework.

You can use any balanced binary tree (e.g. a red-black tree) where in each node you cache the number of items stored in that subtree. The items themselves can be stored in the leaves. For indexed lookup, you compare the index with the size of the left subtree. If it's smaller, it's there. Otherwise it's in the right side, so subtract the size of the left subtree from the index to get the index relative to the right subtree. Then recurse. Since the tree is balanced, this gives you O(log n).

For the other operations you can use the existing algorithms for red-black trees. You just need some small modifications to keep track of the size. For example, to move an item to the front, you first find it using the algorithm described above, then delete it and reinsert it at the front. Each of these steps is O(log n), so the total runtime is also O(log n).