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 firstname.lastname@example.org. 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.
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 the elements of stack are pairwise sorted
- Check if Queue Elements are pairwise consecutive
- Stack Permutations (Check if an array is stack permutation of other)
- Delete all even elements from a stack
- Check if moves in a stack or queue are possible or not
- Check for balanced parenthesis without using stack
- Check if an array is stack sortable
- Print Stack Elements from Bottom to Top
- Check if the given push and pop sequences of Stack is valid or not
- Sort the given stack elements based on their modulo with K
- Design a stack to retrieve original elements and return the minimum element in O(1) time and O(1) space
- Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
- Find maximum in stack in O(1) without using additional stack
- Check if a queue can be sorted into another queue using a stack
- Stack | Set 3 (Reverse a string using stack)
- Sort a stack using a temporary stack
- Count of Array elements greater than all elements on its left and next K elements on its right
- Spaghetti Stack
- Stack in Python
- Sort a stack using recursion