• + 0 comments

    C++ code solution

    vector<int> Permutation(vector<int> arr, int k){
        vector<int>result;
        int size = arr.size();
        int start = 0;
        int end = k;
        int count = 0;
        while(start < size){
            swap(arr[start], arr[end]);
            count++;
            if (k != 1){
                start = start + 1;
                end = end + 1;
                if (count == k){
                    start = start + k;
                    end = end + k;
                    count = 0;
                }
            } else {
                if (count == 1){
                    start = start + 2*k;
                    end = end + 2*k;
                    count = 0;
                }
            }
        }
        result = arr;
        return result;
    }
    vector<int> absolutePermutation(int n, int k) {
        vector<int> newarr;
        vector<int> result;
        int m = n % k;
        if (k == 0){
            for(int i = 0; i < n; i++){newarr.push_back(i+1);}
            result = newarr;
        }
        else if (k == 1)
        {
            if (n % 2 != 0){newarr.push_back(-1);result = newarr;}
            else {
                for (int i = 0; i < n; i++) newarr.push_back(i+1);
                result = Permutation(newarr, k);
            }
        }
        else {
            if (m != 0){newarr.push_back(-1);result = newarr;}
            else 
            {
                if ((n/k) % 2 != 0){newarr.push_back(-1);result = newarr;}
                else {
                    for (int i = 0; i < n; i++) newarr.push_back(i+1);
                    result = Permutation(newarr, k);}
            }
        }
        return result;
    }