![]() |
VOOZH | about |
Given a positive integer X, the task is to find a permutation of length X such that all subarray sum of length greater than one is not divisible by subarray length. If no permutation of length X exists, then print "Permutation doesn't exist".
Examples:
Input: X = 4
Output: {2, 1, 4, 3}
Explanation: All subarray sum of length greater than 1 isn't divisible by subarray length.Input: X = 3
Output: Permutation doesn't exist
Explanation: subarray sum of length 3 is divisible by subarray length(3)
Approach: To solve the problem follow the below idea:
If X is odd, then there will exist a subarray of length X and their sum is divisible by X. So, permutation will not exist except if X is 1. If X is even, Permutation always exists, we will iterate all even numbers from 2 to X and insert i and i-1 in the permutation. Now the permutation will be like this, -2, 1, 4, 3....X, (X-1), it will not automatically contain a subarray of length greater than 1 such that the subarray sum is divisible by subarray length.
Illustration:
Consider X = 4,
- X is even, then we will start iterating from all even numbers from 2 to X.
- At 2, we will print 2 and 2-1 in the array.
- At 4, we will print 4 and 4-1 in the array.
- Now, the subarray of length 2 - [1, 2], [2, 3], [3, 4], subarray sum is not divisible by 2 the subarray of length 3 - [1, 2, 3], [2, 3, 4], subarray sum is not divisible by 3. the subarray of length 4 -[1, 4], subarray sum is not divisible by 4.
- Now, no subarray sum is not divisible by subarray length.
- So finally, return.
Below are the steps to implement the approach:
Below is the code for the above approach:
2 1 4 3
Time Complexity: O(N)
Auxiliary Space: O(1)