I'm looking for a data structure to implement a random access queue ("straight" queue, not priority). That is, standard queue operations (push to back, delete from front, size/isEmpty), but with the wrinkle that I want to be able to do array-like indexing into the middle of the queue (but not insertion or deletion). (To clarify: I am only adding elements to the back of the queue, and only removing elements from the front.) Think of it like a sliding window with a variable size.
Ideally I'm looking for something supporting O(1) operations, but at a minimum I'd like something with sublinear worst-case.
Note: I'm not looking for an implementation or library, so much as I'm looking for a data structure. (This is a matter of personal curiosity, following a related question asked in a recent exam of mine)
A resizable array would give O(1) amortized cost to insert and delete and O(1) random access.
Alternatively, you could implement the queue using an order statistics tree.
An order statistics tree is basically a binary search tree (specifically a self-balancing one to get efficient performance), but each node stores one additional value, which is the size of the subtree rooted at that node (i.e. the number of nodes below it).
Insertion would involve inserting the value in the biggest position, and deletion would delete from the smallest. Random access would just involve using the sizes of the subtrees to traverse to the node corresponding to the given index.
This would result in O(log n) performance for all operations.
Similar to the above, but simpler implementation-wise, we could just use a standard binary search tree, indexed by an ever-increasing unique ID - every value inserted would get an ID of the last ID inserted plus one. To do random-access, you could just offset the smallest ID in the tree by the given index and look for that ID in the tree.
If the IDs were to ever overflow, you could continue on another BST, and eventually get rid of the first if it empties - doing this isn't ideal, but it may still be simpler that implementing ones own tree (as order statistics trees aren't common in libraries).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With