I have a stream of operations. Each operation is one of:
- Set a number value V at key K
- Remove key K
Only one operation can be executed at a time. I need to keep track of the median of all set values in O(1) time.
Example: Initial state:
values == {}
median == 0
Execute set(0, 5):
values == {0: 5}
median == 5
Execute set(1, 3):
values == {0: 5, 1: 3}
median == 4
Execute set(2, 1):
values == {0: 5, 1: 3, 2: 1}
median == 3
Execute set(1, 10):
values == {0: 5, 1: 10, 2: 1}
median == 5
Execute remove(1):
values == {0: 5, 2: 1}
median == 3
I need to keep track only the median value. I don't care if the numbers in hashmap are stored or not. The set and remove must run in O(1) time. ALTHOUGH the parameters to these functions may be computed in any time complexity(e.g., the sorted index of a number can be computed outside set and be passed as a parameter to set and only verified that it is correct inside of the set function)
I tried computing the necessary sorted indices and passing them as parameters to set and remove but I am not sure how to do it bug free.
I can only see one option to do something like this. Store the collection as a linked list, which will preserve the order and do the insert operation for O(1). The median at insertion can also be modified for O(1). In this case, the insertion location must be specified by the key of the previous node.
Here is c# code:
The difference from your example is that you can't immediately insert an existing key here.
Also, I didn't care at all about the complexity of finding a parameter of location to insert. Although this could be improved, but but not to O(1).