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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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
- Append the elements of queue in mirror-inverse order
- Stack and Queue in Python using queue Module
- Reversing a Queue using another Queue
- Count of Array elements greater than all elements on its left and next K elements on its right
- Reversing a Queue
- Queue in Python
- Queue using Stacks
- Queue of Pairs in C++ STL with Examples
- Sharing a queue among three threads
- Applications of Priority Queue
- Priority Queue | Set 1 (Introduction)
- Queue Interface In Java
- Reverse a path in BST using queue
- Priority Queue in Python
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.