- Arrays, Greedy, Mathematical, Natural Numbers, permutation, Sequence and Series

Generate a permutation of first N natural numbers having count of unique adjacent differences equal to K

Generate a permutation of first N natural numbers having count of unique adjacent differences equal to KGiven two positive integers N and K, the task is to construct a permutation of the first N natural numbers such that all possible absolute differences between adjacent elements is K.Examples:Input: N = 3, K = 1Output: 1 2 3Explanation: Considering the permutation {1, 2, 3}, all possible unique absolute difference of adjacent elements is {1}. Since the count is 1(= K), print the sequence {1, 2, 3} as the resultant permutation.Input: N = 3, K = 2Output: 1 3 2Naive Approach: The simplest approach to solve the given problem is to create an array with elements from 1 to N arranged in ascending order and then traverse the first K elements of the array and reverse the subarray starting at the current index and ending at the last index. After completing the above steps, print the resultant array obtained.Below is the implementation of the above approach:Java  class GFG {                  public static void makeList(int N, int K)    {                int[] list = new int[N];                  for (int i = 1; i 1)                K–;        }                  for (int i = 0;             i < list.length; i++) {            System.out.print(                list[i] + " ");        }    }          public static void main(String[] args)    {        int N = 6;        int K = 3;        makeList(N, K);    }}Output: 6 1 5 4 3 2 Time Complexity: O(N)Auxiliary Space: O(N)Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.