Open In App

Check if an array is stack sortable

Last Updated : 24 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of N distinct elements where elements are between 1 and N both inclusive, check if it is stack-sortable or not. An array A[] is said to be stack sortable if it can be stored in another array B[], using a temporary stack S. The operations that are allowed on array are:

  1. Remove the starting element of array A[] and push it into the stack.
  2. Remove the top element of the stack S and append it to the end of array B.

If all the element of A[] can be moved to B[] by performing these operations such that array B is sorted in ascending order, then array A[] is stack sortable. 

Examples:

Input : A[] = { 3, 2, 1 }
Output : YES
Explanation : 
Step 1: Remove the starting element of array A[] 
        and push it in the stack S. ( Operation 1)
        That makes A[] = { 2, 1 } ; Stack S = { 3 }
Step 2: Operation 1
        That makes A[] = { 1 } Stack S = { 3, 2 }
Step 3: Operation 1
        That makes A[] = {} Stack S = { 3, 2, 1 }
Step 4: Operation 2
        That makes Stack S = { 3, 2 } B[] = { 1 }
Step 5: Operation 2
        That makes Stack S = { 3 } B[] = { 1, 2 }
Step 6: Operation 2
        That makes Stack S = {} B[] = { 1, 2, 3 }
  
Input : A[] = { 2, 3, 1}
Output : NO

Given, array A[] is a permutation of [1, …, N], so let us suppose the initially B[] = {0}. Now we can observe that:

  1. We can only push an element in the stack S if the stack is empty or the current element is less than the top of the stack.
  2. We can only pop from the stack only if the top of the stack is B[end] + 1          as the array B[] will contain {1, 2, 3, 4, …, n}.

If we are not able to push the starting element of the array A[], then the given array is Not Stack Sortable. Below is the implementation of above idea: 

C++

// C++ implementation of above approach.
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if A[] is
// Stack Sortable or Not.
bool check(int A[], int N)
{
    // Stack S
    stack<int> S;
 
    // Pointer to the end value of array B.
    int B_end = 0;
 
    // Traversing each element of A[] from starting
    // Checking if there is a valid operation
    // that can be performed.
    for (int i = 0; i < N; i++)
    {
        // If the stack is not empty
        if (!S.empty())
        {
            // Top of the Stack.
            int top = S.top();
 
            // If the top of the stack is
            // Equal to B_end+1, we will pop it
            // And increment B_end by 1.
            while (top == B_end + 1)
            {
                // if current top is equal to
                // B_end+1, we will increment
                // B_end to B_end+1
                B_end = B_end + 1;
 
                // Pop the top element.
                S.pop();
 
                // If the stack is empty We cannot
                // further perform this operation.
                // Therefore break
                if (S.empty())
                {
                    break;
                }
 
                // Current Top
                top = S.top();
            }
 
            // If stack is empty
            // Push the Current element
            if (S.empty()) {
                S.push(A[i]);
            }
            else
            {
                top = S.top();
 
                // If the Current element of the array A[]
                // if smaller than the top of the stack
                // We can push it in the Stack.
                if (A[i] < top)
                {
                    S.push(A[i]);
                }
                // Else We cannot sort the array
                // Using any valid operations.
                else
                {
                    // Not Stack Sortable
                    return false;
                }
            }
        }
        else
        {
            // If the stack is empty push the current
            // element in the stack.
            S.push(A[i]);
        }
    }
 
    // Stack Sortable
    return true;
}
 
// Driver's Code
int main()
{
    int A[] = { 4, 1, 2, 3 };
    int N = sizeof(A) / sizeof(A[0]);
    check(A, N)? cout<<"YES": cout<<"NO";  
    return 0;
}

                    

Java

// Java implementation of above approach.
import java.util.Stack;
 
class GFG {
 
// Function to check if A[] is
// Stack Sortable or Not.
    static boolean check(int A[], int N) {
        // Stack S
        Stack<Integer> S = new Stack<Integer>();
 
        // Pointer to the end value of array B.
        int B_end = 0;
 
        // Traversing each element of A[] from starting
        // Checking if there is a valid operation
        // that can be performed.
        for (int i = 0; i < N; i++) {
            // If the stack is not empty
            if (!S.empty()) {
                // Top of the Stack.
                int top = S.peek();
 
                // If the top of the stack is
                // Equal to B_end+1, we will pop it
                // And increment B_end by 1.
                while (top == B_end + 1) {
                    // if current top is equal to
                    // B_end+1, we will increment
                    // B_end to B_end+1
                    B_end = B_end + 1;
 
                    // Pop the top element.
                    S.pop();
 
                    // If the stack is empty We cannot
                    // further perform this operation.
                    // Therefore break
                    if (S.empty()) {
                        break;
                    }
 
                    // Current Top
                    top = S.peek();
                }
 
                // If stack is empty
                // Push the Current element
                if (S.empty()) {
                    S.push(A[i]);
                } else {
                    top = S.peek();
 
                    // If the Current element of the array A[]
                    // if smaller than the top of the stack
                    // We can push it in the Stack.
                    if (A[i] < top) {
                        S.push(A[i]);
                    } // Else We cannot sort the array
                    // Using any valid operations.
                    else {
                        // Not Stack Sortable
                        return false;
                    }
                }
            } else {
                // If the stack is empty push the current
                // element in the stack.
                S.push(A[i]);
            }
        }
 
        // Stack Sortable
        return true;
    }
 
// Driver's Code
    public static void main(String[] args) {
 
        int A[] = {4, 1, 2, 3};
        int N = A.length;
 
        if (check(A, N)) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }
 
    }
}
//This code is contributed by PrinciRaj1992

                    

Python3

# Python implementation of above approach
 
 
def check(A, N):
 
    # Stack S
    S = []
 
    # Pointer to the end value of array B.
    B_end = 0
 
    # Traversing each element of A[] from starting
    # Checking if there is a valid operation
    # that can be performed.
    for i in range(N):
 
        # if Stack is not empty
        if len(S) != 0:
            # top of the stack
            top = S[-1]
 
            # If the top of the stack is
            # Equal to B_end+1, we will pop it
            # And increment B_end by 1.
            while top == B_end + 1:
 
                # if current top is equal to
                # B_end+1, we will increment
                # B_end to B_end+1
                B_end = B_end + 1
 
                # Pop the top element
                S.pop()
 
                # If the stack is empty We cannot
                # further perform this operation.
                # Therefore break
                if len(S) == 0:
                    break
 
                # Current top
                top = S[-1]
 
            # If stack is empty
            # Push the Current element
            if len(S) == 0:
                S.append(A[i])
            else:
                top = S[-1]
 
                # If the Current element of the array A[]
                # if smaller than the top of the stack
                # We can push it in the Stack.
                if A[i] < top:
                    S.append(A[i])
 
                # Else We cannot sort the array
                # Using any valid operations.
                else:
                    # Not Stack Sortable
                    return False
 
        else:
            # If the stack is empty push the current
            # element in the stack.
            S.append(A[i])
 
    return True
 
 
# Driver's Function
if __name__ == "__main__":
    A = [4, 1, 2, 3]
    N = len(A)
    if check(A, N):
        print("YES")
    else:
        print("NO")

                    

C#

using System;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to check if A[] is
  // Stack Sortable or Not.
  static bool check(int[] A, int N)
  {
 
    // Stack S
    Stack<int> S = new Stack<int>();
 
    // Pointer to the end value of array B.
    var B_end = 0;
 
    // Traversing each element of A[] from starting
    // Checking if there is a valid operation
    // that can be performed.
    for (int i = 0; i < N; i++)
    {
 
      // If the stack is not empty
      if (S.Count != 0)
      {
 
        // Top of the Stack.
        int top = S.Peek();
 
        // If the top of the stack is
        // Equal to B_end+1, we will pop it
        // And increment B_end by 1.
        while (top == B_end + 1)
        {
 
          // if current top is equal to
          // B_end+1, we will increment
          // B_end to B_end+1
          B_end = B_end + 1;
 
          // Pop the top element.
          S.Pop();
 
          // If the stack is empty We cannot
          // further perform this operation.
          // Therefore break
          if (S.Count == 0) {
            break;
          }
 
          // Current Top
          top = S.Peek();
        }
 
        // If stack is empty
        // Push the Current element
        if (S.Count == 0) {
          S.Push(A[i]);
        }
        else {
          top = S.Peek();
 
          // If the Current element of the array
          // A[] if smaller than the top of the
          // stack We can push it in the Stack.
          if (A[i] < top) {
            S.Push(A[i]);
          }
          else
          {
 
            // Not Stack Sortable
            return false;
          }
        }
      }
      else
      {
 
        // If the stack is empty push the current
        // element in the stack.
        S.Push(A[i]);
      }
    }
 
    // Stack Sortable
    return true;
  }
 
  // Driver's Code
  public static void Main(string[] args)
  {
    int[] A = {4, 1, 2, 3};
    int N = A.Length;
    if (check(A, N)) {
      Console.WriteLine("YES");
    }
    else {
      Console.WriteLine("NO");
    }
  }
}
 
// This code is contributed by aadityaburujwale.

                    

Javascript

// JS implementation of above approach.
 
 
// Function to check if A[] is
// Stack Sortable or Not.
function check(A, N) {
    // Stack S
    let S = [];
 
    // Pointer to the end value of array B.
    let B_end = 0;
 
    // Traversing each element of A[] from starting
    // Checking if there is a valid operation
    // that can be performed.
    for (let i = 0; i < N; i++) {
        // If the stack is not empty
        if (S.length != 0) {
            // Top of the Stack.
            let top = S[0];
 
            // If the top of the stack is
            // Equal to B_end+1, we will pop it
            // And increment B_end by 1.
            while (top == B_end + 1) {
                // if current top is equal to
                // B_end+1, we will increment
                // B_end to B_end+1
                B_end = B_end + 1;
 
                // Pop the top element.
                S.shift();
 
                // If the stack is empty We cannot
                // further perform this operation.
                // Therefore break
                if (S.length == 0) {
                    break;
                }
 
                // Current Top
                top = S[0];
            }
 
            // If stack is empty
            // Push the Current element
            if (S.length != 0) {
                S.push(A[i]);
            }
            else {
                top = S[0];
 
                // If the Current element of the array A[]
                // if smaller than the top of the stack
                // We can push it in the Stack.
                if (A[i] < top) {
                    S.push(A[i]);
                }
                // Else We cannot sort the array
                // Using any valid operations.
                else {
                    // Not Stack Sortable
                    return false;
                }
            }
        }
        else {
            // If the stack is empty push the current
            // element in the stack.
            S.push(A[i]);
        }
    }
 
    // Stack Sortable
    return true;
}
 
// Driver's Code
let A = [4, 1, 2, 3];
let N = A.length;
check(A, N) ? console.log("YES") : console.log("NO");
 
 
// This code is contributed by adityamaharshi21

                    

Output:

YES

Time Complexity: O(N)

Auxiliary Space: O(N) because using stack



Previous Article
Next Article

Similar Reads

Stack Permutations (Check if an array is stack permutation of other)
A stack permutation is a permutation of objects in the given input queue which is done by transferring elements from the input queue to the output queue with the help of a stack and the built-in push and pop functions. The rules are: Only dequeue from the input queue.Use inbuilt push, and pop functions in the single stack.Stack and input queue must
15+ min read
Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
Conversion of infix to postfix expression can be done elegantly using two precedence function. Each operator is assigned a value (larger value means higher precedence) which depends upon whether the operator is inside or outside the stack. Also the right and left associativity for different operators can be handled by varying it's values in the two
12 min read
Find maximum in stack in O(1) without using additional stack
The task is to design a stack which can get the maximum value in the stack in O(1) time without using an additional stack. Examples: Input: push(2) findMax() push(6) findMax() pop() findMax() Output: 2 inserted in stack Maximum value in the stack: 2 6 inserted in stack Maximum value in the stack: 6 Element popped Maximum value in the stack: 2 Appro
11 min read
Reversing a Stack with the help of another empty Stack
Given a Stack consisting of N elements, the task is to reverse the Stack using an extra stack. Examples: Input: stack = {1, 2, 3, 4, 5} Output: 1 2 3 4 5 Explanation: Input Stack: 5 4 3 2 1 Reversed Stack: 1 2 3 4 5 Input: stack = {1, 3, 5, 4, 2} Output: 1 3 5 4 2 Approach 1: Follow the steps below to solve the problem: Initialize an empty stack.Po
8 min read
Sort a stack using a temporary stack
Given a stack of integers, sort it in ascending order using another temporary stack. Examples: Input : [34, 3, 31, 98, 92, 23] Output : [3, 23, 31, 34, 92, 98] Input : [3, 5, 1, 4, 2, 8] Output : [1, 2, 3, 4, 5, 8] Recommended PracticeSort a stackTry It! Algorithm: Create a temporary stack say tmpStack.While input stack is NOT empty do this: Pop an
6 min read
Find maximum in stack in O(1) without using additional stack in Python
The task is to design a stack which can get the maximum value in the stack in O(1) time without using an additional stack in Python. Examples: Input: Consider the following SpecialStack 16 –&gt; TOP29151918When getMax() is called it should return 29, which is the maximum element in the current stack. If we do pop two times on stack, the stack becom
3 min read
Check if all array elements are present in a given stack or not
Given a stack of integers S and an array of integers arr[], the task is to check if all the array elements are present in the stack or not. Examples: Input: S = {10, 20, 30, 40, 50}, arr[] = {20, 30}Output: YesExplanation:Elements 20 and 30 are present in the stack. Input: S = {50, 60}, arr[] = {60, 50}Output: YesExplanation:Elements 50 and 60 are
5 min read
Check if a queue can be sorted into another queue using a stack
Given a Queue consisting of first n natural numbers (in random order). The task is to check whether the given Queue elements can be arranged in increasing order in another Queue using a stack. The operation allowed are: Push and pop elements from the stack Pop (Or Dequeue) from the given Queue. Push (Or Enqueue) in the another Queue. Examples : Inp
9 min read
Check if the elements of stack are pairwise sorted
Given a stack of integers, write a function pairWiseSorted() that checks whether numbers in the stack are pairwise sorted or not. The pairs must be increasing, and if the stack has an odd number of elements, the element at the top is left out of a pair. The function should retain the original stack content. Only following standard operations are al
6 min read
Check if the given push and pop sequences of Stack is valid or not
Given push[] and pop[] sequences with distinct values. The task is to check if this could have been the result of a sequence of push and pop operations on an initially empty stack. Return "True" if it otherwise returns "False". Examples: Input: pushed = { 1, 2, 3, 4, 5 }, popped = { 4, 5, 3, 2, 1 }Output: TrueFollowing sequence can be performed:pus
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg