Note: the below code happens to be C#, but really an answer in any language would be helpful for me.
Suppose rather than an actual collection (e.g., a List<T>
), I have a sequence of operations, each looking something like this:
struct ListOperation<T>
{
public enum OperationType { Insert, Remove }
public OperationType Type;
public T Element; // irrelevant for OperationType.Remove
public int Index;
}
Is there some way to efficiently "reconstruct" a collection based on a sequence of such operations?
In particular, I'm looking to avoid the obvious (inefficient) implementation of basically just creating a List<T>
and calling Insert
and RemoveAt
—both O(N) operations—for every element.
Update: Let's say the "sequence" of operations is in fact a concrete collection whose count is known and which is randomly accessible by index (so, like a ListOperation<T>[]
, for example). Let's also say the actual count of the resulting collection is already known (but really, that would be trivial to figure out in O(N) anyway, by counting insertions and removals). Any other ideas?