0

Given a continuous stream of integers and two stacks. I want to implement extractMin operation which runs in O(1) complexity. This operation pops out minimum element from record and returns it. Basic solution is to keep the data in reverse sorted order using 2 stacks. This way we can simply pop out the top element of stack containing data. But with this, insertion is O(N) for every integer. Can I get better complexity in insertion, keeping the extractMin operation to be O(1).

Adding example to make it more clear:

10,-20,2,-3,-5,10,20 (integer stream at any moment).

extractMin() // returns -20
extractMin() // returns -5
revs
  • 53
  • 7

1 Answers1

2

You cannot get better complexity using stacks. Even though you ask for constant extract using stacks, the wording of the question doesn't seem to explicitly ban the use of other data structures.

In earlier version of my answer I suggested min heap, which has constant insert in average through the building of the heap (individual insert is logarithmic in worst case). A heap doesn't however allow constant extraction, but only logarithmic.

To get constant extraction for more than one value, you need to have all the values sorted. One way to achieve that in better complexity than the stacks is to build a binary search tree, while keeping track of the smallest node. Using a balanced bst, you can achieve logarithmic insert. To get constant individual extraction, you also need to store a parent pointer in each node. But if you just need to iterate through all values in order, then you don't need the pointer.

eerorika
  • 181,943
  • 10
  • 144
  • 256
  • Are you sure about O(1) average? As far as I understand then it could be used for O(n) average time comparison sort, which is provably impossible. – sbarzowski Jan 10 '16 at 19:36
  • 1
    @sbarzowski (removed my earlier comments for better reply) You're correct to suspect my complexity analyses because they would indeed allow linear sort. The insert is [conśtant in average](http://stackoverflow.com/questions/9755721/how-can-building-a-heap-be-on-time-complexity). But I promised extract being constant, which it's not. – eerorika Jan 10 '16 at 20:27
  • I think the balanced bst (with parent links) works giving amortized O(log N) inserts (where N is the maximum size of the tree), but the details are quite tricky. In particular, you have to rebalance the tree before the next insert after a sequence of pops. – Paul Hankin Jan 11 '16 at 02:55