An implementation of a queue , using two stacks and , is given below:
void insert (Q, x) {
push (S1, x);
}
void delete (Q) {
if (stack-empty(S2)) then
if (stack-empty(S1)) then {
print(“Q is empty”);
return;
}
else while (!(stack-empty(S1))){
x=pop(S1);
push(S2,x);
}
x=pop(S2);
}
Let insert and delete operations be performed in an arbitrary order on an empty queue . Let and be the number of push and pop operations performed respectively in the process. Which one of the following is true for all and ?
View worked solution
Answer: A
To find the number of push operations () and pop operations (), let us track the movement of elements between the two stacks and :
- Push Operations ():
- Each of the
insertoperations performs exactly push onto . This contributes pushes. - During the
deleteoperations, some elements are transferred from to . Each transferred element requires push onto . - Since successful deletes are performed, at least elements must be transferred to , so .
- Since only elements are ever inserted, at most elements can be transferred, so .
- Thus, the total number of pushes is . Since , we have:
- Each of the
- Pop Operations ():
- The elements transferred from to must be popped from . This contributes pops.
- Each of the
deleteoperations pops exactly element from . This contributes pops. - Thus, the total number of pops is . Since , we have:
Combining these bounds, we get and , which matches Option A.
Free practice · Your answers on this page are not saved.
