• + 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;
    }