Lily's Homework

Sort by

recency

|

26 Discussions

|

  • + 0 comments

    Here is solution in python, java, c++, c and javascript - https://programmingoneonone.com/hackerrank-lilys-homework-problem-solution.html

  • + 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;
    }
    
  • + 0 comments

    include

    using namespace std;

    string ltrim(const string &); string rtrim(const string &); vector split(const string &);

    int countSwapsToTarget(const vector& arr, const vector& target) { int n = arr.size(); unordered_map pos; pos.reserve(n * 2); for (int i = 0; i < n; ++i) pos[target[i]] = i; vector p(n); for (int i = 0; i < n; ++i) p[i] = pos[arr[i]]; vector vis(n, 0); int cycles = 0; for (int i = 0; i < n; ++i) { if (vis[i]) continue; ++cycles; int u = i; while (!vis[u]) { vis[u] = 1; u = p[u]; } } return n - cycles; }

    int lilysHomework(vector arr) { vector asc = arr; sort(asc.begin(), asc.end()); vector desc = asc; reverse(desc.begin(), desc.end()); int swapsAsc = countSwapsToTarget(arr, asc); int swapsDesc = countSwapsToTarget(arr, desc); return min(swapsAsc, swapsDesc); }

    int main() { ofstream fout(getenv("OUTPUT_PATH")); string n_temp; getline(cin, n_temp); int n = stoi(ltrim(rtrim(n_temp))); string arr_temp_temp; getline(cin, arr_temp_temp); vector arr_temp = split(rtrim(arr_temp_temp)); vector arr(n); for (int i = 0; i < n; i++) { int arr_item = stoi(arr_temp[i]); arr[i] = arr_item; } int result = lilysHomework(arr); fout << result << "\n"; fout.close(); return 0; }

    string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) ); return s; }

    string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), s.end() ); return s; }

    vector split(const string &str) { vector tokens; string::size_type start = 0; string::size_type end = 0; while ((end = str.find(" ", start)) != string::npos) { tokens.push_back(str.substr(start, end - start)); start = end + 1; } tokens.push_back(str.substr(start)); return tokens; }

  • + 0 comments

    Solution in Python 3

    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    #
    # Complete the 'lilysHomework' function below.
    #
    # The function is expected to return an INTEGER.
    # The function accepts INTEGER_ARRAY arr as parameter.
    #
    
    def countSwaps(arr, r):
        arr = arr.copy()
        target = sorted(arr, reverse = r)
        inds = {v:i for i,v in enumerate(target)}
        i = 0
        count = 0
        while i < len(arr) and arr != target:
            while arr[i] != target[i]:
                ind = inds[arr[i]]
                arr[i], arr[ind] = arr[ind], arr[i]
                count += 1
            i += 1
        return count
    
    def lilysHomework(arr):
        #Write your code here
        return min(countSwaps(arr, False), countSwaps(arr, True))
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        n = int(input().strip())
    
        arr = list(map(int, input().rstrip().split()))
    
        result = lilysHomework(arr)
    
        fptr.write(str(result) + '\n')
    
        fptr.close()
    
  • + 0 comments
    #include <bits/stdc++.h>
    /*
     * Difficulty Medium
     * Max Score 40
     * https://www.hackerrank.com/challenges/lilys-homework/
     */
    
    using namespace std;
    
    vector <string> split_string(string);
    
    // Complete the lilysHomework function below.
    int lilysHomework(vector<int> arr_orig) {
        int result = INT_MAX;
    
    
        vector<int> sorted(arr_orig);
        sort(sorted.begin(), sorted.end(), greater<int>());
    
        for (int rev = 0; rev < 2; rev++) {
            int curSwap = 0;
            if (rev) {
                reverse(sorted.begin(), sorted.end());
            }
            vector<int> arr(arr_orig);
            // val, pos
            unordered_map<int, int> val2pos;
            for (int i = 0; i < arr.size(); i++) {
                val2pos[arr[i]] = i;
            }
    
    
            for (int i = 0; i < arr.size(); i++) {
                if (arr[i] == sorted[i]) {
                    continue;
                }
                int ai = arr[i];
                int si = sorted[i];
    
                swap(arr[i], arr[val2pos[si]]);
                curSwap++;
    
    
                val2pos[ai] = val2pos[si];
                val2pos[si] = i;
    
    
            }
    
            result = min(result, curSwap);
    
        }
    
    
        return result;
    
    
    }
    
    int main() {
        ofstream fout(getenv("OUTPUT_PATH"));
    
        int n;
        cin >> n;
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    
        string arr_temp_temp;
        getline(cin, arr_temp_temp);
    
        vector <string> arr_temp = split_string(arr_temp_temp);
    
        vector<int> arr(n);
    
        for (int i = 0; i < n; i++) {
            int arr_item = stoi(arr_temp[i]);
    
            arr[i] = arr_item;
        }
    
        int result = lilysHomework(arr);
    
        fout << result << "\n";
    
        fout.close();
    
        return 0;
    }
    
    vector <string> split_string(string input_string) {
        string::iterator new_end = unique(input_string.begin(), input_string.end(), [](const char &x, const char &y) {
            return x == y and x == ' ';
        });
    
        input_string.erase(new_end, input_string.end());
    
        while (input_string[input_string.length() - 1] == ' ') {
            input_string.pop_back();
        }
    
        vector <string> splits;
        char delimiter = ' ';
    
        size_t i = 0;
        size_t pos = input_string.find(delimiter);
    
        while (pos != string::npos) {
            splits.push_back(input_string.substr(i, pos - i));
    
            i = pos + 1;
            pos = input_string.find(delimiter, i);
        }
    
        splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
    
        return splits;
    }