Using a dictionary will not be particularly effective. I recommend something like (self-balancing) a binary search tree (BST).
I say "something like" because we actually do not want to explicitly store priorities, because otherwise we need to update many of them often.
Each node must have a count
its children, so when passing through a tree by insertion or deletion, we know whether to go left or right based on count
nodes. After removal, we can also back up the tree and update count
s.
According to BST, inserting and deleting will take O(log n)
.
You will need to implement this data structure yourself, as this is a modified version of BST, but implementing something like a red-black tree is not too difficult.
Likewise, perhaps something like any modified sorted container.
You will probably need this structure in addition to your current container, as it seems to you that you need to view with string
.
This is a more effective solution, but it is a bit more effort.
source share