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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Check if stack elements are pairwise consecutive
- Check if Queue Elements are pairwise consecutive | Set-2
- Check if Queue Elements are pairwise consecutive
- 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)
- Modulus of all pairwise consecutive elements in an Array
- Product 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 moves in a stack or queue are possible or not
- Check whether the given string is Palindrome using Stack
- Check for balanced parenthesis without using stack
- Check if an array is stack sortable
- 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
- Check if a binary tree is sorted level-wise or not
- Design a stack to retrieve original elements and return the minimum element in O(1) time and O(1) space
- 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 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.