in DS recategorized by
3,976 views
1 vote
1 vote

Which of the following permutations can be obtained in the output using a stack of size 3 elements assuming that input, sequence is 1, 2, 3, 4, 5?

  1. 3, 2, 1, 5, 4
  2. 5, 4, 3, 2, 1
  3. 3, 4, 5, 2, 1
  4. 3, 4, 5, 1, 2
in DS recategorized by
4.0k views

2 Answers

5 votes
5 votes
Best answer

A.

Operation Push(1) Push(2) Push(3) Pop Pop Pop Push(4) Push(5) Pop Pop
      3              
    2 2 2       5    
  1 1 1 1 1   4 4 4  
          Output       3 32 321 321 321 3215 32154

C.

Operation Push(1) Push(2) Push(3) Pop Push(4) Pop Push(5) Pop Pop Pop
      3   4   5      
    2 2 2 2 2 2 2    
  1 1 1 1 1 1 1 1 1  
          Output       3 3 34 34 345 3452 34521

 

Both Option(A) and (C) satisfied here.

selected by
2 votes
2 votes
A and C are valid...

Just insert the elements into the stack as per given order...here order is given 1,2,3,4,5...

So if input contains any order which doesn't follow this is invalid...

 

For D..

insert 1,2,3 into the stack now top symbol is similar to the  input symbol just pop it...

After popping 3 top of the stack is 2 not matched with remaining first input symbol...

So insert 4 into stack..Now matched pop it...

Same way insert 5 and pop it...

Now the I input symbol is 1 but top of the stack is 2...so this sequence is not followed

For B...

1,2,3 ,4,5  we need to insert but our stack size is 3 so not possible...

For A..

Push 1,2,3 now top matches so pop 3,2,1...

Push 4,5 top matches with input so pop 5,4

For C..

push 1,2,3, top match with input 3 so pop it...

Now push 4 , top matches with input so pop 4

Now push 5, top matches with input so pop 5,2,1
edited by

4 Comments

How (B) is possible?
0
0
Simply insert all from 1 to 5 and then top of stack and input matches so remove it...
0
0
how you can insert 5 elements? Given stack size is 3 here.
0
0
Sorry ... Mistake in reading... I'll update...
0
0
Answer:

Related questions