• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
July 04, 2022 |3.4K Views
Check if a queue can be sorted in another queue using a stack
  Share   Like
Description
Discussion

Given a Queue consisting of first n natural numbers (in random order). The task is to check whether the given Queue elements can be arranged in increasing order in another Queue using a stack. The operation allowed are: 


1. Push and pop elements from the stack 
2. Pop (Or Dequeue) from the given Queue. 
3. Push (Or Enqueue) in the another Queue.

 

Observe, second Queue (which will contain the sorted element) takes inputs (or enqueue elements) either from given Queue or Stack. So, the next expected (which will initially be 1) element must be present as a front element of a given Queue or top element of the Stack. So, simply simulate the process for the second Queue by initializing the expected element as 1. 

 

And check if we can get the expected element from the front of the given Queue or from the top of the Stack. If we cannot take it from either of them then pop the front element of the given Queue and push it in the Stack. 


Check if a queue can be sorted in another queue using a stack : https://www.geeksforgeeks.org/check-queue-can-sorted-another-queue-using-stack/