![]() |
VOOZH | about |
Given an integer N, the task is to generate a permutation of elements in the range [1, N] in such order that the length of LIS from starting is equal to LIS from the end of the array. Print -1 if no such array exists.
Examples:
Input: N = 5
Output: [1, 3, 5, 4, 2]
Explanation:
LIS from left side: [1, 3, 5]
LIS from right side: [2, 4, 5]
Length of LIS from left and right side is same that is 3.Input: N = 7
Output: [1, 3, 4, 7, 6, 5, 2]
Explanation:
LIS from left side: [1, 3, 4, 7]
LIS from right side: [2, 5, 6, 7]
Length of LIS from left and right side is same that is 4.
Approach: Use the below observation to solve this problem:
- If N = 2, then such an array doesn't exist.
- Else if N is odd,
- Then start by adding 1 at index 0 and adding 2 at index N-1.
- Now, add N at index N/2. After that, if N>3 then add remaining numbers 3, 4, 5, ... so on indices 1, 2, ..., (N/2-1).
- Now add remaining numbers in decreasing order from index N/2+1 to N-2.
- If N is even,
- say 4 then it has only 1 possible solution: {2, 1, 4, 3}.
- After 4, suppose N = 6, then just add 6 at starting and 5 at ending to the previous answer for N = 4 which forms array = [6, 2, 1, 4, 3, 5].
- Similarly, for next even N just add N at 0th index and N-1 at last index..
Follow the steps mentioned below to solve the problem:
Below is the implementation of the above approach:
1 3 4 7 6 5 2
Time Complexity: O(N)
Auxiliary Space: O(N)