![]() |
VOOZH | about |
Given the integers N and X, the task is to find the smallest lexicographical permutation a[], using all integers [1, N] such that a[i]%i is equal to 0 given that the a[1] = X (the first element of permutation) and a[N] = 1 (the last element of permutation) which means a[1], a[N] are constants and the elements from indices [2, N - 1] should follow a[i] % i = 0.
Note: Follow 1-based indexing
Examples:
Input: N = 4, X = 2
Output: 2 4 3 1
Explanation: The a[1] = 2, a[4] = 1 and a[2]%2, a[3]%3 is equal to 0 so the given condition as per question is satisfied and it is the smallest lexicographical permutation.Input: N = 5, X = 4
Output: -1
Explanation: There is no such possible permutation that satisfies the given condition.
Approach: To solve the problem follow the below approach:
The approach is based on the logic that out of integers of permutation from 1 to N, 1 and X are placed and the Xth indexed position should be replaced by smallest multiple of X. Hashing is used to check whether any number to be placed at ith position is already used or not.
Follow the steps mentioned below to solve the problem:
Below is the implementation of the above approach:
2 4 3 1 -1
Time Complexity: O(nlogn), where n is the size of the array.
Auxiliary Space: O(n)