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)
My Personal Notes arrow_drop_up
- 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
- queue::emplace() in C++ STL
- Queue using Stacks
- queue::swap() in C++ STL
- Reversing a Queue
- Priority Queue in Python
- Priority Queue | Set 1 (Introduction)