Given 2 input stacks with elements in an unsorted manner. Problem is to merge them into a new final stack, such that the elements become arranged in a sorted manner.
Input : s1 : 9 4 2 1 s2: 8 17 3 10 Output : final stack: 1 2 3 4 8 9 10 17 Input : s1 : 5 7 2 6 4 s2 : 12 9 3 Output : final stack: 2 3 4 5 6 7 9 12
Create an empty stack to store result. We first insert elements of both stacks into the result. Then we sort the result stack.
Sorted and merged stack : 34 31 23 12 3 1
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.
- Merging two unsorted arrays in sorted order
- Sorting array using Stacks
- Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted
- Know Your Sorting Algorithm | Set 1 (Sorting Weapons used by Programming Languages)
- Know Your Sorting Algorithm | Set 2 (Introsort- C++’s Sorting Weapon)
- Sorting objects using In-Place sorting algorithm
- Check if the two given stacks are same
- Queue using Stacks
- Bubble sort using two Stacks
- Implement two stacks in an array
- Iterative Postorder Traversal | Set 1 (Using Two Stacks)
- Find maximum sum possible equal sum of three stacks
- Infix to Prefix conversion using two stacks
- Sudo Placement[1.3] | Playing with Stacks
- Efficiently merging two sorted arrays with O(1) extra space
- How to efficiently implement k stacks in a single array?
- Efficiently merging two sorted arrays with O(1) extra space and O(NlogN + MlogM)
- k-th missing element in an unsorted array
- Maximize sum of topmost elements of S stacks by popping at most N elements
- Kth smallest or largest element in unsorted Array | Set 4
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.
Improved By : manishshaw1