Describe a data structure where:
- Any item is indexed by an integral value like in an array
- an integer can index a single value
- integers used to index items are contiguous: they go from 1 to
nwithout holes
- Getting the item at position
i(ie: the item associated to the integeri) should be as fast as possible- random access
- Inserting a new item at position
ishould be as fast as possible- this will right-shift any item from
ionwards
- this will right-shift any item from
- Removing an item at position
ishould also be as fast as possible- this will left-shift any item from
i+1onwards
- this will left-shift any item from
EDIT: a little thing I forgot about: item indices can only be shifted when adding/removing one, they cannot be randomly swapped.
In this description n is the size of the structure (ie: how many items it contains), and i is a generic integer (1 <= i <= n), of course.
I heard this from a guy I met in my faculty. Don’t know if it’s an interview question, an exam question, just a riddle or what, but I guess it could be everything.
If I recall correctly (but hey, it was before December 24th) he said such a data structure could be implemented either with O(sqrt n) insertion/remotion and O(1) access time, or with O(log n) for any operation.
EDIT: Some right answers have been given. Read it if you don’t want to think any more about this problem.
Well, any kind of self-balancing binary tree (e.g., red-black) will provide all three operations for
O(logn). C++ map RB mentioned is one example (if I didn’t forget C++ completely).As for the indexing (
getoperation), there’s a standard trick. We’ll store in each node how many nodes its left subtree has. Now we can locate element at positioniinO(logn)time in a manner like thisObviously, each time element is added or removed,
leftCountvalues will have to be recomputed, but that’ll need to be done only forO(logn)nodes. (think how many nodes include removed one in their left subtree – only the ones directly between it and root)