Check if a queue can be sorted into another queue using a stack in Python


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 −

  • Push or pop elements from stack
  • Delete element from given Queue.
  • Insert element in the other Queue.

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 −

  • n := size of que
  • stk := a new stack
  • exp_val := 1
  • front := null
  • while que is not empty, do
    • front := front element of que
    • remove front element from que
    • if front is same as exp_val, then
      • exp_val := exp_val + 1
    • otherwise,
      • if stk is empty, then
        • push front into stk
      • otherwise when stk is not empty and top of stk < front, then
        • return False
      • otherwise,
        • push front into stk
    • while stk is not empty and top of stack is same as exp_val, do
      • pop from stk
      • exp_val := exp_val + 1
  • if exp_val - 1 is same as n and stk is empty, then
    • return True
  • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

from queue import Queue
def solve(que):
   n = que.qsize()
   stk = []
   exp_val = 1
   front = None
   while (not que.empty()):
      front = que.queue[0]
      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))

Input

[6, 1, 2, 3, 4, 5]

Output

True

Updated on: 29-Dec-2020

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements