Sort by

recency

|

538 Discussions

|

  • + 0 comments

    solution in javascript:

    function absolutePermutation(n, k) {
       const useSet = new Set();
       const res = [];
       
       for(let i = 1; i<=n; i++){
        if((i-k)>=1 && !useSet.has(i-k)){
            res.push(i-k);
            useSet.add(i-k);
        } else if((i+k) <= n && !useSet.has(i+k)){
            res.push(i+k);
            useSet.add(i+k);
        } else{
            return [-1];
        }
       }
       
       return res;
    }
    
  • + 0 comments

    So, I initially used list.contains which creates a problem regarding time complexity(O(N2)). Then, chatGPT suggested to use another means of checking if it's used or not..But the logic works and is originally mine.

    public static List<Integer> absolutePermutation(int n, int k) {
        List<Integer> result = new ArrayList<>();
        boolean[] used = new boolean[n + 1];
    
        for (int i = 1; i <= n; i++) {
            if (i - k > 0 && !used[i - k]) {
                result.add(i - k);
                used[i - k] = true;
            } else if (i + k <= n && !used[i + k]) {
                result.add(i + k);
                used[i + k] = true;
            } else {
                return Arrays.asList(-1);
            }
        }
        return result;
    }
    
  • + 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