# Check if an array is stack sortable in C++

C++Server Side ProgrammingProgramming

Suppose we have an array nums of unique elements from 1 through n. We have to check whether it is stack-sortable or not. An array is stack sortable when it can be stored in some other array using a temporary stack.

To solve this, we can use any of these operations on the array −

• Delete the starting element of array and push that item into the stack.

• Delete the top element of the stack and insert it to the end of second array.

Now if all the element of the given array is transferred to the second array by these operations so the second array is sorted in non-decreasing order, then the given array is stack sortable.

So, if the input is like nums = [8, 6, 5, 3, 1], then the output will be True as we can rotate two times to the clockwise direction then it will be sorted like [1, 3, 4, 5, 6, 8]

To solve this, we will follow these steps −

• Define one stack stk
• last := 0
• for initialize i := 0, when i < size of v, update (increase i by 1), do −
• if stk is not empty, then −
• top := top element of stk
• while top is same as (last + 1), do −
• last := last + 1
• pop from stk
• if stk is empty, then:
• Come out from the loop
• top := top element of stk
• if stk is empty, then:
• push v[i] into stk
• Otherwise
• top := top element of stk
• if v[i] < top, then:
• push v[i] into stk
• Otherwise
• return false
• Otherwise
• push v[i] into stk
• return true

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool solve(vector<int> &v) {
stack<int> stk;
int last = 0;
for (int i = 0; i < v.size(); i++) {
if (!stk.empty()){
int top = stk.top();
while (top == last + 1) {
last = last + 1;
stk.pop();
if (stk.empty()){
break;
} top = stk.top();
}
if (stk.empty()) {
stk.push(v[i]);
}else{
top = stk.top();
if (v[i] < top){
stk.push(v[i]);
}else{
return false;
}
}
}else{
stk.push(v[i]);
}
} return true;
}
main(){
vector<int>
v = {8, 6, 5, 3, 1};
cout << solve(v);
}

## Input

{8, 6, 5, 3, 1}

## Output

1