Consider an ordinary stack of integers that implements the usual push ) and pop(
ID: 3870223 • Letter: C
Question
Consider an ordinary stack of integers that implements the usual push ) and pop( operations in constant time. Describe an algorithm that implements an auxiliary stack alongside the ordinary stack such that the push ) and pop ) operations occur in constant time, but also keep track of the element currently in the ordinary stack with the minimum value in constant time. That is, design the auxiliary stack with these operations such that a user can push ), pop ), and findMin any number of times and still perform these operations in constant time.Explanation / Answer
As push() and pop() operations will complete in constant time i.e 0(1).
So as we need to implement ordinary stack and auxiliary stack
we would need to have two stacks to implement stack to ensure 0(1) and
we need to make sure that minimum value is in ordinary stack.
So we will have two stacks
1) ordinary stack
2) Auxiliary stack
Push,pop and minimum_value will be implemented as below :
int minimum_value()
{
return auxiliaryStack.top();
}
int pop()
{
if( ordinaryStack.isEmpty())
{
return -1;
}
int aux_top = auxiliaryStack.top();
int ord_top = ordinaryStack.top();
if( aux_top == ord_top)
{
auxiliaryStack.pop();
}
return ordinaryStack.pop();
}
int push(int value)
{
ordinaryStack.push(value);
/* checking condition for minimum value, if it is minimum then push data to auxiliaryStack */
if ( auxiliaryStack.isEmpty() || auxiliaryStack.top() >= value)
{
auxiliaryStack.push(value);
}
}