Sort by

recency

|

536 Discussions

|

  • + 0 comments

    Here is problem solution in python java c++ c and Javascript - https://programmingoneonone.com/hackerrank-absolute-permutation-problem-solution.html

  • + 1 comment

    Hi everybody, With n =10 and k = 1, i obtain 2 3 4 5 6 7 8 9 10 9 but the expected output is 2 1 4 3 6 5 8 7 10 9

    Does somebody could explain why my output is not considered as a good answer ?

    Thanks

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

    Easy python

    def absolutePermutation(n, k):
        if k == 0: return list(range(1,n+1))
        if (n/k)%2 != 0: return [-1]
        res = []
        up = True
        for i in range(n//k):
            for j in range(k):
                res.append(i*k+1+j + (k if up else -k))
            up = not up
            
            
        return  res
    
  • + 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:]