Given a stack of integers, write a function pairWiseConsecutive() that checks whether numbers in the stack are pairwise consecutive or not. The pairs can be increasing or decreasing, and if the stack has an odd number of elements, the element at the top is left out of a pair. The function should retain the original stack content.
Only following standard operations are allowed on stack.
- push(X): Enter a element X on top of stack.
- pop(): Removes top element of the stack.
- empty(): To check if stack is empty.
Input : stack = [4, 5, -2, -3, 11, 10, 5, 6, 20] Output : Yes Each of the pairs (4, 5), (-2, -3), (11, 10) and (5, 6) consists of consecutive numbers. Input : stack = [4, 6, 6, 7, 4, 3] Output : No (4, 6) are not consecutive.
The idea is to use another stack.
- Create an auxiliary stack aux.
- Transfer contents of given stack to aux.
- Traverse aux. While traversing fetch top two elements and check if they are consecutive or not. After checking put these elements back to original stack.
Yes Stack content (from top) after function call 20 6 5 10 11 -3 -2 5 4
Time complexity: O(n).
Auxiliary Space : O(n).
This article is contributed by Prakriti Gupta. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Check for balanced parentheses in an expression
- Reverse a stack using recursion
- Spaghetti Stack
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- Implement Stack using Queues
- Iterative Postorder Traversal | Set 2 (Using One Stack)
- Design a stack with operations on middle element
- Sort a stack using recursion
- Check if a given array can represent Preorder Traversal of Binary Search Tree
- Check if two trees are Mirror
- Design a stack that supports getMin() in O(1) time and O(1) extra space
- Implement a stack using single queue
- Find maximum difference between nearest left and right smaller elements
- Stack Class in Java
- Stack | Set 2 (Infix to Postfix)