O(n) time complexity O(1) space complexity in c++


#1

vector Solution::subUnsort(vector &A) {

if(A.size()<=1) return {-1};
int n=A.size();
int left =-1,right=-1;
int ptr1 = 0,ptr2=1;

for(;ptr2<n;ptr2++)
{
    if(A[ptr1]>A[ptr2])
    {
        int temp = ptr2+1;
        while(temp<n)
        {
            if(A[temp]<A[ptr2])
            {
               ptr2=temp;
            }
            temp++;
        
        }
        while(ptr1>=0 && A[ptr1]>A[ptr2])
        {
            // cout<<ptr1<<" "<<ptr2<<endl;
            ptr1--;
        }
        left = ptr1+1;
        break;
    }
    else
    {
        ptr1++;
    }
}
if(left ==-1 ) return {-1};
ptr1 =n-2,ptr2=n-1;
for(;ptr1>=0;ptr1--)
{
    if(A[ptr1]>A[ptr2])
    {
        int temp = ptr1-1;
        while(temp>=0)
        {
            if(A[temp]>A[ptr1])
            {
               ptr1=temp;
            }
            temp--;
        
        }
         while(ptr2<n && A[ptr1]>A[ptr2])
        {
            ptr2++;
        }
        right = ptr2-1;
        break;
    }
    else
    {
        ptr2--;
    }
}
return {left,right};

}