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 | Set-2
- Check if Queue Elements are pairwise consecutive
- 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)
- Check if a queue can be sorted into another queue using a stack
- 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
- Stack | Set 3 (Reverse a string using stack)
- Sort a stack using a temporary stack
- stack empty() and stack size() in C++ STL
- 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 all array elements are present in a given stack or not
- Check if an array is stack sortable
- Check for balanced parenthesis without using stack
- Check if the given push and pop sequences of Stack is valid or not
- Check if moves in a stack or queue are possible or not
- Check whether the given string is Palindrome using Stack
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.