VOOZH about

URL: https://www.geeksforgeeks.org/dsa/smallest-lexicographical-permutation-such-that-ai-i-is-equal-to-0/

⇱ Smallest lexicographical permutation such that a[i] % i is equal to 0 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest lexicographical permutation such that a[i] % i is equal to 0

Last Updated : 14 Feb, 2023

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:

  • Initialize the check[] array to check whether the element to be placed at the ith index is visited or not.
  • Initialize vector permutation to store the final result permutation.
  • Initialize a flag variable to check if there is a possibility to form a permutation.
  • As given in the question, mark 1 and x as visited as they are placed.
  • Traverse from 2 till N
  • Now, check for the number to be placed at ith position to satisfy the condition. Iterate from j = i to all multiples of j to place the lowest possible multiple.
  • If the element itself is not visited already then place it.
  • Else, check for a multiple that is not visited and divides N.
  • If the ith indexed element is still -1 we are unable to find an element to place so mark the flag and break.
  • Print -1 if not possible to form a permutation
  • Print the permutation if it is possible to form a permutation.

Below is the implementation of the above approach:


Output
2 4 3 1 
-1

Time Complexity: O(nlogn), where n is the size of the array.
Auxiliary Space: O(n) 

Comment