Suppose we have a Queue with first n natural numbers (unsorted). We have to check whether the given Queue elements can be sorted in non-decreasing sequence in another Queue by using a stack. We can use following operations to solve this problem −
So, if the input is like Que = [6, 1, 2, 3, 4, 5], then the output will be True as we can pop 6 from Que, then push it into stack. Now pop all remaining elements from Que to another queue, then pop 6 from stack and push into the second queue, so all elements in the new queue will be sorted in non-decreasing sequence.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
from queue import Queue def solve(que): n = que.qsize() stk =  exp_val = 1 front = None while (not que.empty()): front = que.queue que.get() if (front == exp_val): exp_val += 1 else: if (len(stk) == 0): stk.append(front) elif (len(stk) != 0 and stk[-1] < front): return False else: stk.append(front) while (len(stk) != 0 and stk[-1] == exp_val): stk.pop() exp_val += 1 if (exp_val - 1 == n and len(stk) == 0): return True return False que = Queue() items = [6, 1, 2, 3, 4, 5] for i in items: que.put(i) print(solve(que))
[6, 1, 2, 3, 4, 5]