• + 0 comments

    Simple approach in python:

        P = [0]*(n+1)
        # Try to create P that fulfills |P[i] - i| = k
        for i in range(1,n+1):
            if P[i] == 0:
                # P[i] can be either i+k or i-k.
                # Greedy approach, try to fit the lexicographically smallest first
                if i-k > 0 and P[i-k] == 0:
                    P[i], P[i-k] = i-k, i
                elif i+k <= n and P[i+k] == 0:
                    P[i], P[i+k] = i+k, i
                else:
                    # Not possible
                    return [-1]
        # Skips the first element, added just for better code readability
        return P[1:]