Check if Queue Elements are pairwise consecutive in Python

A queue contains numbers and we need to check if consecutive pairs of elements are pairwise consecutive (differ by exactly 1). This means we group elements in pairs and verify each pair has consecutive numbers.

So, if the input is like que = [3,4,6,7,8,9], then the output will be True because pairs (3,4), (6,7), and (8,9) are all consecutive.

Algorithm

To solve this, we will follow these steps −

  • Create a queue and insert all elements from the given list
  • Extract all elements from queue into a temporary list
  • Reverse the order by moving elements to another list
  • Process pairs from the reversed list and check if each pair differs by 1
  • Return True if all pairs are consecutive, False otherwise

Example

Let us see the following implementation to get better understanding −

import queue

def solve(que):
    q = queue.Queue()
    for i in que:
        q.put(i)
    
    # Extract all elements from queue
    temp = []
    while q.qsize() != 0:
        temp.append(q.queue[0])
        q.get()
    
    # Reverse the order
    temp2 = []
    while len(temp) != 0:
        temp2.append(temp[len(temp) - 1])
        temp.pop()
    
    result = True
    
    # Check pairs for consecutive property
    while len(temp2) > 1:
        x = temp2[len(temp2) - 1]
        temp2.pop()
        y = temp2[len(temp2) - 1]
        temp2.pop()
        
        if abs(x - y) != 1:
            result = False
        
        q.put(x)
        q.put(y)
    
    # Handle odd number of elements
    if len(temp2) == 1:
        q.put(temp2[len(temp2) - 1])
    
    return result

# Test the function
que = [3,4,6,7,8,9]
print(solve(que))
True

Alternative Approach

Here's a simpler approach without using queue data structure −

def check_pairwise_consecutive(numbers):
    # Process pairs from the list
    for i in range(0, len(numbers) - 1, 2):
        if i + 1 < len(numbers):
            if abs(numbers[i] - numbers[i + 1]) != 1:
                return False
    return True

# Test cases
test1 = [3, 4, 6, 7, 8, 9]
test2 = [1, 2, 5, 6, 3, 4]
test3 = [1, 3, 5, 7]

print(f"[3,4,6,7,8,9]: {check_pairwise_consecutive(test1)}")
print(f"[1,2,5,6,3,4]: {check_pairwise_consecutive(test2)}")
print(f"[1,3,5,7]: {check_pairwise_consecutive(test3)}")
[3,4,6,7,8,9]: True
[1,2,5,6,3,4]: True
[1,3,5,7]: False

How It Works

The algorithm processes elements in pairs:

  • For queue [3,4,6,7,8,9], pairs are: (3,4), (6,7), (8,9)
  • Check if |3-4| = 1 ?, |6-7| = 1 ?, |8-9| = 1 ?
  • All pairs are consecutive, so return True

Conclusion

To check if queue elements are pairwise consecutive, group elements in pairs and verify each pair differs by exactly 1. The simpler approach directly processes the list without complex queue operations.

Updated on: 2026-03-25T15:23:05+05:30

307 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements