Lily's Homework

  • + 2 comments

    I have done the same thing but still i am not getting the answer

    int lilysHomework(vector<int> arr) {
        int swaps=0;
        vector<int> sorted;
        sorted=arr;
        sort(sorted.begin(),sorted.end());
        map<int,int> count;
        for(int i=0;i<arr.size();i++)
            count[arr[i]]=i;
    
        for(int i=0;i<arr.size();i++){
            if(arr[i]!=sorted[i]){
                swaps++;
                int temp1=arr[i],temp2=sorted[i];
                swap(arr[i],arr[count[temp2]]);
                count[temp1]=count[temp2];
            }
        }
    
        return swaps;
    }
    

    For the input

    3 4 2 5 1
    

    I am doing these swaps

    1 4 2 5 3 
    1 2 4 5 3 
    1 2 3 5 4 
    1 2 3 4 5
    

    Total swaps here are 4 but the expected outcome is 2

    What am I doing wrong here?