Skip to content
Related Articles

Related Articles

Sudo Placement[1.3] | Playing with Stacks
  • Difficulty Level : Expert
  • Last Updated : 15 Dec, 2020

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:  

C++




// C++ program for
// Sudo Placement | playing with stacks
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if it is possible
// count the number of steps
void countSteps(int sa[], int n)
{
 
    // Another stack
    stack<int> sc;
 
    // variables to count transfers
    int required = 1, transfer = 0;
 
    // iterate in the stack in reverse order
    for (int i = 0; i < n; i++) {
 
        // if the last element has to be
        // inserted by removing elements
        // then count the number of steps
        if (sa[i] == required) {
            required++;
            transfer++;
        }
        else {
            // if stack is not empty and top element
            // is smaller than current element
            if (!sc.empty() && sc.top() < sa[i]) {
                cout << "NO";
                return;
            }
            // push into stack and count operation
            else {
 
                sc.push(sa[i]);
                transfer++;
            }
        }
        // stack not empty, then pop the top element
        // pop out all elements till is it equal to required
        while (!sc.empty() && sc.top() == required) {
            required++;
            sc.pop();
            transfer++;
        }
    }
 
    // print the steps
    cout << "YES " << transfer;
}
 
// Driver Code
int main()
{
    int sa[] = { 4, 3, 1, 2, 5 };
    int n = sizeof(sa) / sizeof(sa[0]);
    countSteps(sa, n);
    return 0;
}

Java




// Java program for Sudo
// Placement | playing with stacks
import java.util.*;
 
class GFG
{
 
    // Function to check if it is possible
    // count the number of steps
    static void countSteps(int sa[], int n)
    {
 
        // Another stack
        Stack<Integer> sc = new Stack<Integer>();
 
        // variables to count transfers
        int required = 1, transfer = 0;
 
        // iterate in the stack in reverse order
        for (int i = 0; i < n; i++)
        {
 
            // if the last element has to be
            // inserted by removing elements
            // then count the number of steps
            if (sa[i] == required)
            {
                required++;
                transfer++;
            }
            else
            // if stack is not empty and top element
            // is smaller than current element
            if (!sc.empty() && sc.peek() < sa[i])
            {
                System.out.print("NO");
                return;
            }
             
            // push into stack and count operation
            else
            {
 
                sc.push(sa[i]);
                transfer++;
            }
            // stack not empty, then pop the top element
            // pop out all elements till is it equal to required
            while (!sc.empty() && sc.peek() == required)
            {
                required++;
                sc.pop();
                transfer++;
            }
        }
 
        // print the steps
        System.out.println("YES " + transfer);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int sa[] = {4, 3, 1, 2, 5};
        int n = sa.length;
        countSteps(sa, n);
    }
}
 
/* This code contributed by PrinciRaj1992 */

Python3




# Python3 program for
# Sudo Placement | playing with stacks
from typing import List
 
# Function to check if it is possible
# count the number of steps
def countSteps(sa: List[int], n: int) -> None:
     
    # Another stack
    sc = []
 
    # Variables to count transfers
    required = 1
    transfer = 0
     
    # Iterate in the stack in reverse order
    for i in range(n):
         
        # If the last element has to be
        # inserted by removing elements
        # then count the number of steps
        if (sa[i] == required):
            required += 1
            transfer += 1
             
        else:
             
            # If stack is not empty and top element
            # is smaller than current element
            if (sc and sc[-1] < sa[i]):
                print("NO")
                return
 
            # push into stack and count operation
            else:
                sc.append(sa[i])
                transfer += 1
 
        # stack not empty, then pop the top
        # element pop out all elements till
        # is it equal to required
        while (sc and sc[-1] == required):
            required += 1
            sc.pop()
            transfer += 1
 
    # Print the steps
    print("YES {}".format(transfer))
 
# Driver Code
if __name__ == "__main__":
 
    sa = [ 4, 3, 1, 2, 5 ]
    n = len(sa)
     
    countSteps(sa, n)
 
# This code is contributed by sanjeev2552

C#




// C# program for Sudo
// Placement | playing with stacks
using System;
using System.Collections.Generic;   
     
public class GFG
{
  
    // Function to check if it is possible
    // count the number of steps
    static void countSteps(int []sa, int n)
    {
  
        // Another stack
        Stack<int> sc = new Stack<int>();
  
        // variables to count transfers
        int required = 1, transfer = 0;
  
        // iterate in the stack in reverse order
        for (int i = 0; i < n; i++)
        {
  
            // if the last element has to be
            // inserted by removing elements
            // then count the number of steps
            if (sa[i] == required)
            {
                required++;
                transfer++;
            }
            else
            // if stack is not empty and top element
            // is smaller than current element
            if (sc.Count!=0 && sc.Peek() < sa[i])
            {
                Console.Write("NO");
                return;
            }
              
            // push into stack and count operation
            else
            {
  
                sc.Push(sa[i]);
                transfer++;
            }
            // stack not empty, then pop the top element
            // pop out all elements till is it equal to required
            while (sc.Count!=0 && sc.Peek() == required)
            {
                required++;
                sc.Pop();
                transfer++;
            }
        }
  
        // print the steps
        Console.WriteLine("YES " + transfer);
    }
  
    // Driver Code
    public static void Main(String[] args)
    {
        int []sa = {4, 3, 1, 2, 5};
        int n = sa.Length;
        countSteps(sa, n);
    }
}
// This code has been contributed by 29AjayKumar
Output: 
YES 7

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :