Stable Mex help(don't know why its coming wrong)

problem link : Contest Page | CodeChef

Problem Code: STBMEX

my code :slight_smile:

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int t,j,i;
    cin>>t;
	while(t--)
	{
	    long long int n,mex = -1,res = 0,flag = 0;
	    cin>>n;
	    long long int a[n];
	    for(i = 0; i<n;i++)
	        cin>>a[i];
	   
	   
	   sort(a,a+n);
	   long num = 0;
	       
	       
	   for(i = 0; i<n - 1;i++)
	   {
	       if(a[i] == a[i+1])
	           continue;
	       if(a[i] == num)
	           num++;
	       else
	       {
	           flag = 1;
	           mex = num;
	           break;
	       }
	       
	   }
	   if(flag == 0)
	   {
    	   if(a[i] == num)
    	    mex = num + 1;
    	   else 
    	    mex = num;
	   }
	   // cout<<mex<<endl;
	    

	    long long int temp = mex - 1;
	    j= 1;
	    if(mex == 0)
	        cout<<a[0] - 1<<endl;
	    else if(mex == 1)
	        cout<<-1<<endl;
	   else
      {
    	   for( i = mex;i<n - 1;i++)
    	   {
    	           if(a[i] == a[i+1])
	                   continue;
    	           if(a[i] == a[i + 1] - 1)
    	           {
    	               //cout<<a[i]<<" "<<j<<endl;
    	               j++;
    	               if(j == temp)
    	                res++;
    	           }
    	           else
    	            j = 1;
    	            
    	        
    	   }
    	   cout<<res<<endl;
      }
	   
	   
	}
	return 0;
}

Hey @coder2kdash :wave: ,
Your code is failing for the test case
1
5
8 0 1 0 1
correct answer is 1 your output is 0.