• + 0 comments

    A simple python solution that passes all the test cases consists of doing +k -k operations then give privilege to - k operation if applicable else + k operation if applicable to get the smallest P. If - k and + k can not be possible return -1. NOTE that using a set to test if the element has been already used is mandatory, otherwise test cases from 9 to 12 will exceed allowed time:

    def absolutePermutation(n, k):
        res = []
        used = set()
        for index in range(1, n + 1):
            lower_option = index - k
            upper_option = index + k
            if lower_option > 0 and lower_option not in used:
                res.append(lower_option)
                used.add(lower_option)
            elif upper_option <= n and upper_option not in used:
                res.append(upper_option)
                used.add(upper_option)
            else:
                return [-1]
        return res