• + 0 comments

    c++ solution:

    vector<int> absolutePermutation(int n, int k) {
        if (k == 0) {
            vector<int> permutation(n, 0);
            for (int index = 0; index < n; index++) {
                permutation[index] = index + 1;
            }
            return permutation;
        }
        
        // we need an even count of k-chucks in order to find an absolute permutation
        if (k > n / 2 || n % k != 0 || (n / k) % 2 != 0) {
            return { -1 };
        }
        
        vector<int> permutation(n, 0);
        // process two chucks in a single iteration
        for (int indexChucks = 0; indexChucks < n; indexChucks += 2 * k) {
            for (int indexElement = 0; indexElement < k; indexElement++) {
                int index = indexChucks + indexElement;
                permutation[index] = k + index + 1;
                permutation[k + index] = index + 1;
            }
        }
        
        return permutation;
    }