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
- Take a variable n to store size of queue.
- Push an element to the queue which acts as marker.
- Now, If size of queue is odd, start popping a pair while n > 2. Also, while popping these pairs, check for their difference and decrease n by 2, if there difference is not equal to 1, set flag to false.
- If size of queue is even, start popping a pair while n > 1. Also, while popping these pairs, check for their difference and decrease n by 2, if their difference is not equal to 1, set flag to false.
- Finally, check flag, if it is true, it means elements in the queue are pairwise sorted, else not.
Below is the implementation of above approach:
Time Complexity: O(n)
Auxiliary Space: O(1)
- Check if Queue Elements are pairwise consecutive
- Modulus of all pairwise consecutive elements in an Array
- 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::front() and queue::back() in C++ STL
- queue::push() and queue::pop() in C++ STL
- Reversing a Queue using another Queue
- queue::swap() in C++ STL
- Reversing a Queue
- queue::emplace() in C++ STL
- Queue in Python
- Queue using Stacks
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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