0

From this, we can design data structure special stack with method getMin() which should return minimum element from the SpecialStack.

My question is: How to implement the method getMed() which should return the medium element from the SpecailStack?

From this Data Structure to find median, we know the best data structure is two heaps. Left is a Max-Heap; Right is a Min-Heap. However, for my question it seems not good, because the top element pushed into stack must be maintained which heap can not do that. Am I right?

Edit I do not know how to maintain the index of latest pushed element with Heap.

Thanks a lot.

Community
  • 1
  • 1
zangw
  • 43,869
  • 19
  • 177
  • 214
  • Can you clarify what you mean by "because the top element pushed into stack must be maintained which heap can not do that"? What cannot be maintained? Do you want to maintain your stack after the algorithm completes? – nmore Aug 05 '14 at 01:22
  • @nmore I mean the special stack should maintain the index of the last pushed element, so `pop()` can be implemented easily, I don't know how to do it with heap. – zangw Aug 05 '14 at 01:28
  • Ok I understand the problem now. The two heap algorithm is used when you get a bunch of data all at once and then have to find the median of it. However here you have the benefit of getting the elements one at a time. I suggest that as you get them, maintain a sorted list of all the elements. However, pop and push will be O(log(n)), but getMid() will be O(1). This will make the common use of your stack more costly though, so depending on your use of getMid(), consider recalculating the mid with the two heap algorithm each time you need it. – nmore Aug 05 '14 at 01:34

2 Answers2

2

You could alternatively use an Order Statistic Tree.

John Kurlak
  • 6,594
  • 7
  • 43
  • 59
0

You can use any balanced binary search tree here instead of a heap. It is easy to find min or max element in a tree(the leftmost and the rightmost node), and it also supports deletion in O(log N).

So you can maintain a stack and two binary search trees(instead of two heaps). Push implementation is pretty strainforward. To pop an element, you can delete the top element from a tree where it is stored, adjust the trees(like in two heaps algorithm) and then pop it from the stack.

kraskevich
  • 18,368
  • 4
  • 33
  • 45
  • How about only use one balanced binary search tree? To maintain the root node as the medium element in the stack through adjusting the tree. – zangw Aug 05 '14 at 11:19
  • @zangw Yes, it is possible to do it with one tree. However, it would require using a custom tree. For my algorithm, standard binary search tree like std::multiset in C++ is sufficient. – kraskevich Aug 05 '14 at 13:10