Short question:
Is there any data structure or algorithm that allows retrievals, insertions and deletions by index in constant time?
In detail, I want to solve the following problem (in Java):
Given a collection of positive numbers, create a data structure that allows to do the following operations granting constant time (can use up to 50-70MB):
Obtain the maximum or minimum element (is enough with only one) at any moment.
Remove and insert at a given index.
I tried to have the elements in a sorted array, and every time the top (maximum or minimum) element is deleted, mark it with a negative number then, increase an index pointing to the top element, for example:
# sortedArr[headIndex] = topElement
sortedArr = [30, 20, 9, 5, 3, 2, 1]
headIndex = 0
Delete top element (30)
sortedArr = [-1, 20, 9, 5, 3, 2, 1]
headIndex = 1
Delete top element again (20)
sortedArr = [-1, -1, 9, 5, 3, 2, 1]
headIndex = 2
The problem comes when the deleted element is not the top one, as I would lose track of the top element:
# sortedArr[headIndex] = topElement
sortedArr = [-1, -1, 9, 5, 3, 2, 1]
headIndex = 2
Delete number "3"
sortedArr = [-1, -1, 9, 5, -1, 2, 1]
headIndex = 2 # It is not updated as no top element has been removed.
Delete number "5" and "9"
sortedArr = [-1, -1, -1, -1, -1, 2, 1]
headIndex = ?
HeadIndex should be 5, but the problem is that updating headIndex, in the way that, every time there is a deletion, headIndex points to the new top element seems not possible, for that is why ask for the above data structure.
Something like double stack structure, that allowed deletions and insertions anywhere would fit me.