Given a stack of integers, write a function pairWiseSorted() that checks whether numbers in the stack are pairwise sorted or not.
The pairs must be increasing, 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 the 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: 4, 5, 6, 7, 8, 9 Output: Yes Input: 4, 9, 2, 1, 10, 8 Output: No
Approach: 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 sorted or not.
- After checking put these elements back to original stack.
Below is the implementation of above approach:
Yes Stack content (from top) after function call 6 5 11 10 -2 -3 5 4
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 stack elements are pairwise consecutive
- Check if Queue Elements are pairwise consecutive
- Check if Queue Elements are pairwise consecutive | Set-2
- Check if a queue can be sorted into another queue using a stack
- Minimum number of elements to be removed so that pairwise consecutive elements are same
- Stack Permutations (Check if an array is stack permutation of other)
- Product of all pairwise consecutive elements in an Array
- Modulus of all pairwise consecutive elements in an Array
- Absolute Difference of all pairwise consecutive elements in an array
- Delete all even elements from a stack
- Print Stack Elements from Bottom to Top
- Check if an array is stack sortable
- Check for balanced parenthesis without using stack
- Check if moves in a stack or queue are possible or not
- Check whether the given string is Palindrome using Stack
- Sort the given stack elements based on their modulo with K
- Check if the given push and pop sequences of Stack is valid or not
- Design a stack to retrieve original elements and return the minimum element in O(1) time and O(1) space
- Check if a binary tree is sorted level-wise or not
- Minimum elements inserted in a sorted array to form an Arithmetic progression
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.