What can be best suited data structure that supports the following operations in O(log n) time:
search(x) finds the element with key x
insert(x) insert an element with a key x
delete(x) delete an element with a key x
deleteLast() removes the most recently inserted element
I know that a binary search tree can handle first three operations pretty good. But how to handle fourth query. If BST is not a good solution than also tell what can be best suited data structure for handling all four queries.
Credit to @ThomasJungblut for bringing this solution up.
First, build a BST to hold the information you need in the leaves of the tree.
This in it self solves the search, insert & delete requirements.
To address the "delete most recently inserted element" requirement we add to the structure of each leaf
prev&nextfields, so this:Becomes this:
And except for holding the root of the BST, also hold
leaf *last. Every time a new element is added, it point to the one before andlastis updated.Note: This addition only helps finding the requested item, the deletion itself takes
log(n).EDITED thanks to @AlexeiShestakov