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
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.
- 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)
- Sorting objects using In-Place sorting algorithm
- Know Your Sorting Algorithm | Set 2 (Introsort- C++’s Sorting Weapon)
- Check if the two given stacks are same
- Queue using Stacks
- Bubble sort using two Stacks
- Implement two stacks in an array
- Sudo Placement[1.3] | Playing with Stacks
- Infix to Prefix conversion using two stacks
- Find maximum sum possible equal sum of three stacks
- Iterative Postorder Traversal | Set 1 (Using Two 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 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.
Improved By : manishshaw1