C++ approach with explanation

interview-questions
amazon
Tags: #<Tag:0x00007f181de37358> #<Tag:0x00007f181de37128>

#1

// we need to print index of 1st unsorted element and last unsorted element
// else we print -1
vector Solution::subUnsort(vector &A) {
vector B;
vector ans;
B=A;
int max,min;
sort(B.begin(),B.end());
if (B==A) //if B vector and A vector are equal then both is sorted, hence, we return -1’
{
ans.push_back(-1);
return(ans);
}
if (B!=A) // when A is not sorted
{
for (int i=A.size()-1;i>=0;i–) // we start by finding index of max unsorted element
{
if (B[i]!=A[i])
{
max=i;
break;
}
}
for (int j=0;j<A.size();j++) // we find index of 1st unsorted element
{
if (B[j]!=A[j])
{
min=j;
break;
}
}
ans.push_back(min); // push both indices
ans.push_back(max);
}

return(ans);

}