Given a Queue of integers. The task is to check if consecutive elements in the queue are pairwise consecutive.
Input : 1 2 5 6 9 10 Output : Yes Input : 2 3 9 11 8 7 Output : No
Approach : Using two stacks :
- Transfer all elements of the queue to one auxiliary stack aux.
- Now, transfer the elements from this stack to another auxiliary stack aux2.
- Start popping two elements from aux2 and then check the difference between these two elements. If their difference is 1, continue for other pairs till one element is left in the stack.
- Also, after popping, push them to queue simultaneously to maintain the original queue.
- Finally, if there is any pair with a difference not equal to 1, return false, else return true.
Below is the implementation of above approach:
Yes 4 5 -2 -3 11 10 5 6
Time Complexity: O(n), where n is size of queue.
Auxiliary Space: O(n), where n is the size of stack.
- Check if Queue Elements are pairwise consecutive | Set-2
- Check if stack elements are pairwise consecutive
- Check if the elements of stack are pairwise sorted
- Check if a queue can be sorted into another queue using a stack
- Reversing the first K elements of a Queue
- Check if moves in a stack or queue are possible or not
- Stack and Queue in Python using queue Module
- Queue using Stacks
- Reversing a Queue
- Applications of Priority Queue
- Priority Queue | Set 1 (Introduction)
- Reversing a queue using recursion
- Priority Queue in Python
- Sharing a queue among three threads
- Reverse a path in BST using queue
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Rajput-Ji