Open In App

Check if an array is stack sortable

Last Updated : 19 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of n distinct elements, where each element is between 1 and n (inclusive), determine if it is stack-sortable.
Note: An array a[] is considered stack-sortable if it can be rearranged into a sorted array b[] using a temporary stack stk with the following operations:

  1. Remove the first element from a[] and push it into stk.
  2. Remove the top element from stk and append it to b[].

If all elements from a[] can be moved to b[] in this manner, ensuring that b[] is sorted in ascending order, then a[] is stack-sortable.

Examples:

Input: arr[] = [4, 1, 3, 2]
Output: Yes
Explanation: Elements are pushed and popped in the following order:

  • Push 4 (stk = [4])
  • Push 1 (stk = [4, 1]) -> Pop 1 to b = [1]
  • Push 3 (stk = [4, 3])
  • Push 2 (stk = [4, 3, 2]) -> Pop 2 to b = [1, 2]
  • Pop 3 to b = [1, 2, 3]
  • Pop 4 to b = [1, 2, 3, 4]

Since b[] is sorted, arr[] is stack-sortable.


Input: arr[] = [4, 2, 3, 1]
Output: No
Explanation: Elements are pushed and popped in the following order:

  • Push 4 into stk -> stk = [4]
  • Push 2 into stk -> stk = [4, 2]
  • Push 3 into stk -> stk = [4, 2, 3]
  • Push 1 into stk -> stk = [4, 2, 3, 1]

At this point, we try to pop elements in ascending order (1, 2, 3, 4):

  • Pop 1 -> b[] = [1], stk = [4, 2, 3]
  • Pop 3 -> violates sorted order (should be 2 next), so not possible

Given, array arr[] is a permutation of [1, …, n] and we want the order to be number from 1 to n. We keep track of next expected number (initially 1), we pop an item when top of the stack matches the expected number, else push the item to stack. At the end, if our expected number is (n+1), our input array is stack sortable, otherwise not.

Steps to implement the above idea:

  • Initialize an empty stack (stk) and set expected to 1, which represents the next number needed in sorted order.
  • Iterate through arr, pushing each element into stk while checking if the top matches expected.
  • If the top of stk equals expected, pop from stk, increment expected, and continue this process.
  • Repeat popping while stk is not empty and its top matches the expected number in sorted order.
  • If all elements are correctly arranged such that expected == n + 1, return true, otherwise return false.
C++
// C++ program to check if an array is 
// stack-sortable
#include <bits/stdc++.h>
using namespace std;

// Function to check if the array 
// is stack-sortable
bool isStackSortable(vector<int> &arr) {
    
    // Stack to temporarily hold elements
    stack<int> stk;
    
    int n = arr.size();
    
    // Expected number in sorted order
    int expected = 1;

    // Traverse through the array
    for (int num : arr) {
        
        // Push the current element onto the stack
        stk.push(num);
        
        // Pop from stack if it matches the
        // expected number
        while (!stk.empty() 
               && stk.top() == expected) {
                   
            stk.pop();
            expected++;
        }
    }

    // If we have arranged all elements
    // in sorted order
    return expected == n + 1;
}

// Driver code
int main() {
    
    vector<int> arr = {4, 1, 3, 2};

    if (isStackSortable(arr)) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }

    return 0;
}
Java Python C# JavaScript

Output
Yes

Time Complexity: O(n) – Each element is pushed and popped at most once.
Space Complexity: O(n) – The stack (stk) may store all n elements in the worst case.


Article Tags :
Practice Tags :

Similar Reads