Lily's Homework

  • + 0 comments
    int countSwaps(vector<int> arr, vector<int> sortedArr) {
        int n = arr.size();
        unordered_map<int, int> indexMap;
    
        // Mapping each value to its index in the sorted array
        for (int i = 0; i < n; i++)
            indexMap[sortedArr[i]] = i;
    
        vector<bool> visited(n, false);
        int swaps = 0;
    
        for (int i = 0; i < n; i++) {
            // If already visited or already in the correct position, skip
            if (visited[i] || indexMap[arr[i]] == i)
                continue;
    
            // Cycle detection
            int cycleSize = 0;
            int j = i;
            while (!visited[j]) {
                visited[j] = true;
                j = indexMap[arr[j]];
                cycleSize++;
            }
    
            // A cycle of size k requires (k-1) swaps
            if (cycleSize > 1)
                swaps += (cycleSize - 1);
        }
    
    int lilysHomework(vector<int> arr) {
        vector<int> sortedArr = arr;
    
        // Sort in ascending order and count swaps
        sort(sortedArr.begin(), sortedArr.end());
        int swapsAsc = countSwaps(arr, sortedArr);
    
        // Sort in descending order and count swaps
        sort(sortedArr.begin(), sortedArr.end(), greater<int>());
        int swapsDesc = countSwaps(arr, sortedArr);
    
        // Return minimum of the two
        return min(swapsAsc, swapsDesc);
    }
    
    
    
    
    
    
        return swaps;
    }