3,173 views
3 votes
3 votes

Consider an efficient implementation of a data structure STACK-MAX that support an operation “max( )” that reports the current maximum among all elements in the stack. Normal stack operations i.e., push, pop are also to be supported. The size of above data structure after performing following operation push (5), push (6), push (7), pop, max, push (6), push (8), pop, pop, max, push (5) is ________ (in bytes). Assume that an integer can be stored in 4 bytes.

3 Answers

2 votes
2 votes

Ans: 20 bytes

Applying efficient algorithm, 

Main_Stack Max_Stack
5  
8 8
6  
7 7
6 6
5 5

Here, when 7 is pushed, new entry is created in MAX_STACK because it is the new MAX. 

Next element to be pushed is 6. Applying efficient algorithm there is no need to push it in MAX_STACK. 

Similarly, when 8 is pushed, new entry is created in MAX_STACK of new MAX.

Now, coming to POP peration, 8,6,7 are popped from MAIN_STACK and along with it 8 and 7 are also popped from MAX_STACK.

At the end, 5 is pushed on MAIN_STACK and no need to insert it on MAX_STACK.

So, final table is - 

MAIN_STACK MAX_STACK
5  
6 6
5 5

So, total number of elements = 5

Total size = 5*4 bytes = 20 Bytes

PS : Above concept is discussed in Data Structures and Algorithms - Narasimha Karumanchi 

1 votes
1 votes
Ans : 24 bytes.

STACK-MAX supports an operation “max( )” that reports the current maximum among all elements in the stack. Keeping this in mind, lets unfold the problem.

PUSH 5, STACK :
5

PUSH 6, STACK :
6
5

PUSH 7, STACK :
7
6
5

POP, STACK :
6
5

MAX, (In order to find the maximum element in the stack we have go through the entire STACK {O(n)}. So, we would need another stack STACK2. We would POP all the elements of STACK one by one and PUSH them to STACK2. In the process, we capture the maximum element and return it at the end of max() function)
2 elements would be present at STACK2 at this point temporarily and again PUSHed back to STACK to get back the original stack.                                              .............(i)

PUSH 6, STACK :
6
6
5

PUSH 8, STACK :
8
6
6
5
(This is the maximum number of elements that can be present in STACK at a given time)   .......(ii)

POP, STACK :
6
6
5

POP, STACK :
6
5

MAX  .........same as (i)

From (i) and (ii), the maximum number of elements that can be present in STACK = 4 ;
the maximum number of elements that can be present in STACK2 = 2

So, data structure STACK_MAX should contain STACK and STACK2. Size of STACK_MAX = (4+2)*4 bytes = 24 bytes
0 votes
0 votes

the answer is 24 bytes as thats the  maximum size of the array datastructure that can be taken for stcks.

Related questions

0 votes
0 votes
1 answer
1
Abhrajyoti00 asked Oct 29, 2022
737 views
Can there be “Stack Overflow” in Linked list Implementation of stack? If Yes, how?