r/datastructures • u/neuralbeans • Sep 08 '26
A data structure that maps indexes to values (like an array) but that is only populated once and then deletes values by index in sublinear time
There are algorithms that require having a populated array from which the i{th} value is repeatedly removed (which changes the indexes of the values after it) until it is empty. An array removes a value in linear time. Is there a data structure that allows for sublinear time arbitrary value removal?
For example:
start: [A, B, C, D, E]
remove 2: [A, B, D, E]
remove 0: [B, D, E]
remove 2: [B, D]
remove 1: [B]
remove 0: []
On average, removing all the items in arbitrary order is a quadratic time operation. Is there something faster?
16
Upvotes
3
u/neuralbeans Sep 08 '26
My hacky solution:
Use a binary tree with the values being in the leaves only. The leaves contain the values in order from left to right like this:
The intermediate nodes are only there to store the number of leaves their descendants contain. By checking how many leaves the children of a node contain, you can determine which child contains the index of interest.
To find the value at index 2 (C), do the following:
Next, we mark the leaf node as deleted and go back up the path of nodes to the root and decrement the number in each intermediate node.
Now, without having to update any indexes, we can find that the new value at index 2 is D, because following the tree according to the numbers in the intermediate nodes will take us there.
Each deletion will take logarithmic time at the expense of needing twice as much space than an array.
1
u/vanilla-bungee Sep 08 '26
Setting an index in an array to null takes constant time. Do you want the array to shrink and the index of each element updated after a removal?
1
u/Accomplished_Rock894 Sep 09 '26
Ig this is the same as a problem from CSE Range Queries
1
u/Maple-4590 Sep 12 '26
Finger tree