If you need random insertion and deletion, the best way is probably to sort the array. Insertions and removals should be O (log (n)).
Yes, but you will need to re-sort each insert and (possibly) each delete, which, as you said, is O (log (n)).
With the solution proposed by Harprit:
- you have one O (n) pass at the beginning to find the smallest element
- the insert is O (1) after that (only one comparison is needed for the smallest element already known)
- delete will be O (n) because you will need to find the smallest element (remember that Big O notation is the worst case). You can also optimize by checking to see if the item you want to remove is the smallest, and if not, just do not double-check to find the smallest item.
So it depends. One of these algorithms would be better for an insert-heavy use case with multiple deletions, but the other is generally more consistent. I think that I would use Harpreet's mechanism by default if I didnโt know that the smallest number would be deleted often, because this provides a weak point in this algorithm.
source share