VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sudo-placement-playing-with-stacks/

⇱ Sudo Placement[1.3] | Playing with Stacks - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sudo Placement[1.3] | Playing with Stacks

Last Updated : 17 Jan, 2023

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 7 

Input: 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. 

  • if the stack element is equal to the required element, then the number of transfers will be one which is the count of transferring from A to C.
  • if it is not equal to the required element, then check if it is possible to transfer it by comparing it with the topmost element in the stack. 
    1. If the topmost element in stackC is greater than the stackA[i] element, then it is not possible to transfer it in a sorted way,
    2. else push the element to stackC and increment transfer.
  • Iterate in the stackC and pop out the top most element until it is equal to the required and increment required and transfer in every steps.

Below is the implementation of the above approach:  


Output
YES 7

Time Complexity: O(n2)
Auxiliary Space: O(n)

Comment