VOOZH about

URL: https://www.geeksforgeeks.org/dsa/non-divisible-subarray-sum-permutation/

⇱ Non-Divisible Subarray sum permutation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Non-Divisible Subarray sum permutation

Last Updated : 22 Aug, 2023

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:

  • If X is odd, if X is 1, then print 1. else print "permutation doesn't exist" and return.
  • If X is even, iterate from all even numbers from 2 to X.
  • while iterating i, print i and i-1 at every i.
  • Finally, return.

Below is the code for the above approach:


Output
2 1 4 3 

Time Complexity: O(N)
Auxiliary Space: O(1)

Comment