Stack Permutations (Check if an array is stack permutation of other) - GeeksforGeeks

28 Apr, 2022
A stack permutation is a permutation of objects in the given input queue which is done by transferring elements from input queue to the output queue with the help of a stack and the built-in push and pop functions.The well defined rules are:  
Only dequeue from the input queue.Use inbuilt push, pop functions in the single stack.Stack and input queue must be empty at the end.Only enqueue to the output queue.
Only dequeue from the input queue.
Use inbuilt push, pop functions in the single stack.
Stack and input queue must be empty at the end.
Only enqueue to the output queue.
There are a huge number of permutations possible using a stack for a single input queue. Given two arrays, both of unique elements. One represents the input queue and the other represents the output queue. Our task is to check if the given output is possible through stack permutation.Examples:  
Input : First array: 1, 2, 3  
        Second array: 2, 1, 3
Output : Yes
Procedure:
push 1 from input to stack
push 2 from input to stack
pop 2 from stack to output
pop 1 from stack to output
push 3 from input to stack
pop 3 from stack to output


Input : First array: 1, 2, 3  
        Second array: 3, 1, 2
Output : Not Possible  
 
The idea to do this is we will try to convert the input queue to output queue using a stack, if we are able to do so then the queue is permutable otherwise not. Below is the step by step algorithm to do this:  
Continuously pop elements from the input queue and check if it is equal to the top of output queue or not, if it is not equal to the top of output queue then we will push the element to stack.  Once we find an element in input queue such the top of input queue is equal to top of output queue, we will pop a single element from both input and output queues, and compare the top of stack and top of output queue now. If top of both stack and output queue are equal then pop element from both stack and output queue. If not equal, go to step 1.  Repeat above two steps until the input queue becomes empty. At the end if both of the input queue and stack are empty then the input queue is permutable otherwise not.  
Continuously pop elements from the input queue and check if it is equal to the top of output queue or not, if it is not equal to the top of output queue then we will push the element to stack.  
Once we find an element in input queue such the top of input queue is equal to top of output queue, we will pop a single element from both input and output queues, and compare the top of stack and top of output queue now. If top of both stack and output queue are equal then pop element from both stack and output queue. If not equal, go to step 1.  
Repeat above two steps until the input queue becomes empty. At the end if both of the input queue and stack are empty then the input queue is permutable otherwise not.  
Below is implementation of above idea:  
C++
Java
Python3
C#
Javascript
// Given two arrays, check if one array is// stack permutation of other.#include<bits/stdc++.h>using namespace std; // function to check if input queue is// permutable to output queuebool checkStackPermutation(int ip[], int op[], int n){    // Input queue    queue<int> input;    for (int i=0;i<n;i++)        input.push(ip[i]);     // output queue    queue<int> output;    for (int i=0;i<n;i++)        output.push(op[i]);     // stack to be used for permutation    stack <int> tempStack;    while (!input.empty())    {        int ele = input.front();        input.pop();        if (ele == output.front())        {            output.pop();            while (!tempStack.empty())            {                if (tempStack.top() == output.front())                {                    tempStack.pop();                    output.pop();                }                else                    break;            }        }        else            tempStack.push(ele);    }     // If after processing, both input queue and    // stack are empty then the input queue is    // permutable otherwise not.    return (input.empty()&&tempStack.empty());} // Driver program to test above functionint main(){    // Input Queue    int input[] = {1, 2, 3};     // Output Queue    int output[] = {2, 1, 3};     int n = 3;     if (checkStackPermutation(input, output, n))        cout << "Yes";    else        cout << "Not Possible";    return 0;}
// Given two arrays, check if one array is// stack permutation of other.import java.util.LinkedList;import java.util.Queue;import java.util.Stack; class Gfg{    // function to check if input queue is    // permutable to output queue    static boolean checkStackPermutation(int ip[],                                    int op[], int n)    {        Queue<Integer> input = new LinkedList<>();         // Input queue        for (int i = 0; i < n; i++)        {            input.add(ip[i]);        }         // Output queue        Queue<Integer> output = new LinkedList<>();        for (int i = 0; i < n; i++)        {            output.add(op[i]);        }         // stack to be used for permutation        Stack<Integer> tempStack = new Stack<>();        while (!input.isEmpty())        {            int ele = input.poll();             if (ele == output.peek())            {                output.poll();                while (!tempStack.isEmpty())                {                    if (tempStack.peek() == output.peek())                    {                        tempStack.pop();                        output.poll();                    }                    else                        break;                }            }            else            {                tempStack.push(ele);            }        }         // If after processing, both input queue and        // stack are empty then the input queue is        // permutable otherwise not.        return (input.isEmpty() && tempStack.isEmpty());    }     // Driver code    public static void main(String[] args)    {        // Input Queue        int input[] = { 1, 2, 3 };         // Output Queue        int output[] = { 2, 1, 3 };        int n = 3;        if (checkStackPermutation(input, output, n))            System.out.println("Yes");        else            System.out.println("Not Possible");    }} // This code is contributed by Vivekkumar Singh
# Given two arrays, check if one array is# stack permutation of other.from queue import Queue # function to check if Input queue# is permutable to output queuedef checkStackPermutation(ip, op, n):         # Input queue    Input = Queue()    for i in range(n):        Input.put(ip[i])     # output queue    output = Queue()    for i in range(n):        output.put(op[i])     # stack to be used for permutation    tempStack = []    while (not Input.empty()):        ele = Input.queue[0]        Input.get()        if (ele == output.queue[0]):            output.get()            while (len(tempStack) != 0):                if (tempStack[-1] == output.queue[0]):                    tempStack.pop()                    output.get()                else:                    break        else:            tempStack.append(ele)     # If after processing, both Input    # queue and stack are empty then     # the Input queue is permutable    # otherwise not.    return (Input.empty() and        len(tempStack) == 0) # Driver Codeif __name__ == '__main__':     # Input Queue    Input = [1, 2, 3]     # Output Queue    output = [2, 1, 3]     n = 3     if (checkStackPermutation(Input,                              output, n)):        print("Yes")    else:        print("Not Possible") # This code is contributed by PranchalK
// Given two arrays, check if one array is// stack permutation of other.using System;using System.Collections.Generic; class GFG{    // function to check if input queue is    // permutable to output queue    static bool checkStackPermutation(int []ip,                                      int []op, int n)    {        Queue<int> input = new Queue<int>();         // Input queue        for (int i = 0; i < n; i++)        {            input.Enqueue(ip[i]);        }         // Output queue        Queue<int> output = new Queue<int>();        for (int i = 0; i < n; i++)        {            output.Enqueue(op[i]);        }         // stack to be used for permutation        Stack<int> tempStack = new Stack<int>();        while (input.Count != 0)        {            int ele = input.Dequeue();             if (ele == output.Peek())            {                output.Dequeue();                while (tempStack.Count != 0)                {                    if (tempStack.Peek() == output.Peek())                    {                        tempStack.Pop();                        output.Dequeue();                    }                    else                        break;                }            }            else            {                tempStack.Push(ele);            }        }         // If after processing, both input queue and        // stack are empty then the input queue is        // permutable otherwise not.        return (input.Count == 0 && tempStack.Count == 0);    }     // Driver code    public static void Main(String[] args)    {        // Input Queue        int []input = { 1, 2, 3 };         // Output Queue        int []output = { 2, 1, 3 };        int n = 3;        if (checkStackPermutation(input, output, n))            Console.WriteLine("Yes");        else            Console.WriteLine("Not Possible");    }} // This code is contributed by PrinciRaj1992
<script>    // Given two arrays, check if one array is    // stack permutation of other.         // function to check if input queue is    // permutable to output queue    function checkStackPermutation(ip, op, n)    {        let input = [];           // Input queue        for (let i = 0; i < n; i++)        {            input.push(ip[i]);        }           // Output queue        let output = [];        for (let i = 0; i < n; i++)        {            output.push(op[i]);        }           // stack to be used for permutation        let tempStack = [];        while (input.length != 0)        {            let ele = input.shift();               if (ele == output[0])            {                output.shift();                while (tempStack.length != 0)                {                    if (tempStack[tempStack.length - 1] == output[0])                    {                        tempStack.pop();                        output.shift();                    }                    else                        break;                }            }            else            {                tempStack.push(ele);            }        }           // If after processing, both input queue and        // stack are empty then the input queue is        // permutable otherwise not.        return (input.length == 0 && tempStack.length == 0);    }         // Input Queue    let input = [ 1, 2, 3 ];     // Output Queue    let output = [ 2, 1, 3 ];    let n = 3;    if (checkStackPermutation(input, output, n))      document.write("Yes");    else      document.write("Not Possible");         // This code is contributed by rameshtravel07.</script>
Output:  
Yes
Another Approach:  – 
Idea –  we will start iterating on input array and storing its element one by one in a stack and if top of our stack matches with an element in output array we will pop that element from stack and compare next element of output array with top of our stack if again it matches then again pop until our stack isn’t empty 
C++
// Given two arrays, check if one array is// stack permutation of other.#include<bits/stdc++.h>using namespace std; // function to check if input array is// permutable to output arraybool checkStackPermutation(int ip[], int op[], int n){     // we will be pushing elements from input array to stack uptill top of our stack     //  matches with first element of output array      stack<int>s;          // will maintain a variable j to iterate on output array      int j=0;       // will iterate one by one in input array      for(int i=0;i<n;i++)      {        // pushed an element from input array to stack        s.push(ip[i]);        // if our stack isn't empty and top matches with output array        // then we will keep popping out from stack uptill top matches with        // output array        while(!s.empty() and s.top()==op[j])        {          s.pop();          // increasing j so next time we can compare next element in output array          j++;        }      }             // if output array was a correct permutation of input array then      // by now our stack should be empty      if(s.empty())      {        return true;      }      return false;        } // Driver program to test above functionint main(){    // Input Array    int input[] = {4,5,6,7,8};     // Output Array    int output[] = {8,7,6,5,4};     int n = 5;     if (checkStackPermutation(input, output, n))        cout << "Yes";    else        cout << "Not Possible";    return 0;}
Yes
Time Complexity –  O(N)
Space Complexity – O(N)
This article is contributed by Suprotik Dey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
PranchalKatiyar
Vivekkumar Singh
princiraj1992
rameshtravel07
8_bit_spider
surinderdawra388
Combinatorial
Queue
Stack
Stack
Combinatorial
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Combinational Sum
Count ways to reach the nth stair using step 1, 2 or 3
Print all possible strings of length k that can be formed from a set of n characters
Count of subsets with sum equal to X
Python program to get all subsets of given size of a set
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Queue Interface In Java
Queue in Python
Queue | Set 1 (Introduction and Array Implementation)