![]() |
VOOZH | about |
You are given 3 stacks, A(Input Stack), B(Auxiliary Stack) and C(Output Stack). Initially stack A contains numbers from 1 to N, you need to transfer all the numbers from stack A to stack C in sorted order i.e in the end, the stack C should have smallest element at the bottom and largest at top. You can use stack B i.e at any time you can push/pop elements to stack B also. At the end stack A, B should be empty.
Examples:
Input: A = {4, 3, 1, 2, 5}
Output: Yes 7Input: A = {3, 4, 1, 2, 5}
Output: No
Approach: Iterate from the bottom of the given stack. Initialize required as the bottom most element in stackC at the end i.e., 1. Follow the given below algorithm to solve the above problem.
Below is the implementation of the above approach:
YES 7
Time Complexity: O(n2)
Auxiliary Space: O(n)