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

Sometimes we need to check if elements in a queue can be rearranged into sorted order using an auxiliary stack. This problem involves three data structures: an input queue, a stack for temporary storage, and an output queue for the final sorted sequence.

Problem Understanding

Given a queue with the first n natural numbers in unsorted order, we need to determine if we can sort them into non-decreasing sequence using these operations:

  • Push or pop elements from stack
  • Delete element from input queue
  • Insert element into output queue

For example, with queue [6, 1, 2, 3, 4, 5], we can pop 6 and push it to stack, then process remaining elements 1-5 directly to output queue, and finally pop 6 from stack to complete the sorted sequence.

Algorithm Approach

The key insight is to use a stack as temporary storage when elements arrive out of order. We expect elements in sequence (1, 2, 3, ..., n). When an element matches our expected value, we place it directly in the output. Otherwise, we use the stack strategically.

Implementation

from queue import Queue

def can_sort_queue(que):
    n = que.qsize()
    stack = []
    expected_value = 1
    
    while not que.empty():
        front = que.get()
        
        if front == expected_value:
            # Current element is what we expect next
            expected_value += 1
        else:
            # Check if we can use stack
            if stack and stack[-1] < front:
                # Cannot maintain sorted order
                return False
            stack.append(front)
        
        # Pop from stack if top element is what we expect next
        while stack and stack[-1] == expected_value:
            stack.pop()
            expected_value += 1
    
    # Check if all elements are processed and stack is empty
    return expected_value - 1 == n and len(stack) == 0

# Test the function
que = Queue()
items = [6, 1, 2, 3, 4, 5]
for item in items:
    que.put(item)

result = can_sort_queue(que)
print(f"Can sort queue {items}: {result}")
Can sort queue [6, 1, 2, 3, 4, 5]: True

How It Works

Let's trace through the example [6, 1, 2, 3, 4, 5]:

def trace_sorting(items):
    que = Queue()
    for item in items:
        que.put(item)
    
    stack = []
    expected = 1
    output = []
    
    print(f"Initial queue: {items}")
    
    while not que.empty():
        front = que.get()
        print(f"\nProcessing: {front}, Expected: {expected}")
        
        if front == expected:
            output.append(front)
            print(f"  ? Added {front} to output: {output}")
            expected += 1
        else:
            if stack and stack[-1] < front:
                print(f"  ? Cannot sort! Stack top {stack[-1]} < {front}")
                return False
            stack.append(front)
            print(f"  ? Pushed {front} to stack: {stack}")
        
        # Check stack for next expected elements
        while stack and stack[-1] == expected:
            popped = stack.pop()
            output.append(popped)
            print(f"  ? Popped {popped} from stack to output: {output}")
            expected += 1
    
    print(f"\nFinal output: {output}")
    return len(stack) == 0

trace_sorting([6, 1, 2, 3, 4, 5])
Initial queue: [6, 1, 2, 3, 4, 5]

Processing: 6, Expected: 1
  ? Pushed 6 to stack: [6]

Processing: 1, Expected: 1
  ? Added 1 to output: [1]

Processing: 2, Expected: 2
  ? Added 2 to output: [1, 2]

Processing: 3, Expected: 3
  ? Added 3 to output: [1, 2, 3]

Processing: 4, Expected: 4
  ? Added 4 to output: [1, 2, 3, 4]

Processing: 5, Expected: 5
  ? Added 5 to output: [1, 2, 3, 4, 5]
  ? Popped 6 from stack to output: [1, 2, 3, 4, 5, 6]

Final output: [1, 2, 3, 4, 5, 6]

Edge Cases

Let's test a case where sorting is impossible:

# Test impossible case
def test_impossible_case():
    que = Queue()
    items = [3, 1, 2]  # This cannot be sorted
    for item in items:
        que.put(item)
    
    result = can_sort_queue(que)
    print(f"Can sort queue {items}: {result}")

test_impossible_case()
Can sort queue [3, 1, 2]: False

Time and Space Complexity

  • Time Complexity: O(n) - Each element is processed exactly once
  • Space Complexity: O(n) - In worst case, all elements might be stored in stack

Conclusion

This algorithm efficiently determines if a queue can be sorted using a stack by maintaining the invariant that stack elements are in decreasing order. The key insight is that we can only pop from stack when the top element matches our expected next value in the sorted sequence.

---
Updated on: 2026-03-25T14:07:51+05:30

400 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements