I have been doing a question recently and I used a similar approach to the editorial. Link to the question is below : https://www.spoj.com/problems/STPAR/
Editorial Code (Though it is from a third party site, I have tested it and it gives AC)-
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
int a[1111], n;
int main() {
while (scanf("%d", &n) && n != 0) {
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
int k = 0, i = 0;
stack<int> st;
while (i < n) {
while (st.size() && st.top() == k + 1) k++, st.pop();
if (a[i] != k + 1) st.push(a[i]);
else k++;
i++;
}
while (st.size() && st.top() == k + 1) k++, st.pop();
puts(k == n ? "yes" : "no");
}
}
My code -
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
while(t)
{
int n;
cin>>n;
if(n==0)
{
break;
}
int arr[n];
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
int p=1;
stack<int> s;
int flag=0;
for(int i=0; i<n; i++)
{
while(!s.empty() && s.top()==p)
{
s.pop();
p++;
}
if(p==arr[i])
{
p++;
}else if(!s.empty() && s.top()<arr[i])
{
flag=1;
break;
}else{
s.push(arr[i]);
}
}
if(flag==0)
{
cout<<"yes"<<endl;
}else{
cout<<"no"<<endl;}
}
}
I just cannot understand the difference between the two codes as they use the exactly similar approach and the code is almost similar as well. Help would be appreciated :)