Check if an array is stack sortable
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:
- Remove the first element from a[] and push it into stk.
- 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++ 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 program to check if an array is
// stack-sortable
import java.util.Stack;
class GfG {
// Function to check if the array
// is stack-sortable
static boolean isStackSortable(int[] arr) {
// Stack to temporarily hold elements
Stack<Integer> stk = new Stack<>();
int n = arr.length;
// 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.isEmpty()
&& stk.peek() == expected) {
stk.pop();
expected++;
}
}
// If we have arranged all elements
// in sorted order
return expected == n + 1;
}
// Driver code
public static void main(String[] args) {
int[] arr = {4, 1, 3, 2};
if (isStackSortable(arr)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
# Python program to check if an array is
# stack-sortable
# Function to check if the array
# is stack-sortable
def isStackSortable(arr):
# Stack to temporarily hold elements
stk = []
n = len(arr)
# Expected number in sorted order
expected = 1
# Traverse through the array
for num in arr:
# Push the current element onto the stack
stk.append(num)
# Pop from stack if it matches the
# expected number
while stk and stk[-1] == expected:
stk.pop()
expected += 1
# If we have arranged all elements
# in sorted order
return expected == n + 1
# Driver code
if __name__ == "__main__":
arr = [4, 1, 3, 2]
if isStackSortable(arr):
print("Yes")
else:
print("No")
// C# program to check if an array is
// stack-sortable
using System;
using System.Collections.Generic;
class GfG {
// Function to check if the array
// is stack-sortable
public static bool isStackSortable(int[] arr) {
// Stack to temporarily hold elements
Stack<int> stk = new Stack<int>();
int n = arr.Length;
// Expected number in sorted order
int expected = 1;
// Traverse through the array
foreach (int num in arr) {
// Push the current element onto the stack
stk.Push(num);
// Pop from stack if it matches the
// expected number
while (stk.Count > 0
&& stk.Peek() == expected) {
stk.Pop();
expected++;
}
}
// If we have arranged all elements
// in sorted order
return expected == n + 1;
}
// Driver code
public static void Main() {
int[] arr = {4, 1, 3, 2};
if (isStackSortable(arr)) {
Console.WriteLine("Yes");
} else {
Console.WriteLine("No");
}
}
}
// JavaScript program to check if an array is
// stack-sortable
// Function to check if the array
// is stack-sortable
function isStackSortable(arr) {
// Stack to temporarily hold elements
let stk = [];
let n = arr.length;
// Expected number in sorted order
let expected = 1;
// Traverse through the array
for (let num of arr) {
// Push the current element onto the stack
stk.push(num);
// Pop from stack if it matches the
// expected number
while (stk.length > 0
&& stk[stk.length - 1] === expected) {
stk.pop();
expected++;
}
}
// If we have arranged all elements
// in sorted order
return expected === n + 1;
}
// Driver code
let arr = [4, 1, 3, 2];
if (isStackSortable(arr)) {
console.log("Yes");
} else {
console.log("No");
}
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.