Sort by

recency

|

539 Discussions

|

  • + 0 comments
    function absolutePermutation($n, $k) {
        $index = [];
        
        for($i = 1; $i <= $n; $i++) {
            $index[$i] = true;
        }
    
        $found = 0;
        $p = [];
        for($number = 1; $number <= $n; $number++) {
            $need1 = $k + $number;
            $need2 = abs($k - $number);
            if(abs($need2 - $number) === $k && ($index[$need2] ?? false)) {
                $index[$need2] = false;
                $p[] = $need2;
                $found++;
            } else if (abs($need1 - $number) === $k && ($index[$need1] ?? false)) {
                $index[$need1] = false;
                $p[] = $need1;
                $found++;
            }
        }
        
        return $found === $n ? $p : [-1];
    }
    
  • + 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