Adobe Interview Question
Software Engineer / Developers@coder : Heap is not right because it lacks order throughout the tree (Think about insert and than lookup or more deeply about getting the next min/max number after extractmin/max). BST is the right implementation with a min and max variable so that the lookup is O(1) while update takes lg(n). Update(insert, extract) shall also change the min/max variable
Having a balanced BST, is good. But while we are trying perform extractMin() delete the leftmost leaf of the BST, we need to maintain another variable tempMin. Which will be updated as we travel from head to the leftmost node and will hold the prev-min value (at the end the parent of the left-most node). This is what the next min is after removing the Min from the BST in extractMin() operation and stored in Min variable.
Similarly, have tempMax variable to store the previous-max during extractMax() operation.
In fact, the same Min and Max variables can be reused for the tempMin and tempMax purpose.
For every solution, think of a scenario when the currentMin is removed. i.e. extractMin. Now, whatever data structure you propose should provide a way to find out next min/max. The solution provided by Shwetank does not handle this case. Also it is more space complex. And off-source time complex as well.
If the new element that you insert into a linked list is smaller than the current Min? You need to update each node in the list to point to this new Min. How do you say each operation is O(1)?
Use two heaps - minheap and maxheap. Each entry contains integer, and a pointer to the same value on the other heap.
Min and max are constant time as they only require a look up to the appropriate heap's root node.
Extractmin will remove root on minheap, replace the last element of maxheap with node pointed by just removed min node and finally 'heapify' both structures.
Extractmax works symmetrically.
Insert puts value in both heaps and updates the pointers.
All of O(logN) operations will take O(2logN) => still O(logN) bound. May not be space efficient, but solves for the time constraint.
BST with Min and Max.
1) each node while insertion will update the min and max.
2) extractMin is performed then left end child will be updated as Min in root
3) extractMax is performed then right end child will be updated as Max in root
4) for deletion, if min or max node is deleted then do the same thing which is done by extractMin and extracMax.
so Min and Max will be done in O(1) and rest of the operation will be done in O(log2n)
Implement an ADT that encapsulates a BALANCED BST and two variables min and max.
- random September 15, 2009insertion,deletion,extractMin,extractMax would then take O(logn) time
On every insertion update the min and max variables.So max() and min() would take O(1) time.