![]() |
VOOZH | about |
Given two positive integers N and K, the task is to find a permutation P of length N such that the sum of every adjacent pair of elements in P is greater than or equal to K. If there are multiple permutations that satisfy the condition, you should output the lexicographically smallest one. If there is no permutation that satisfies the condition, you should output -1.
Note: In other words, you need to find a permutation P of the numbers [1, 2, ..., N] such that P[i] + P[i+1] ≥ K for all 1 ≤ i ≤ N-1. The lexicographically smallest permutation is the one that comes first in alphabetical order when the numbers are written out in sequence. For example, [1, 2, 3] is lexicographically smaller than [1, 3, 2].
Examples:
Input: N = 6, K = 5
Output: 1 4 2 3 5 6
Explanation: Considering the permutation 1 4 2 3 5 6 sum of adjacent elements is greater than 5. There exists different permutation such as [3, 5, 1, 4, 2, 6], [1, 5, 2, 3, 4, 6], [6, 1, 4, 3, 5, 6]etc. But
[1, 4, 2, 3, 5, 6] is the lexicographically smallest one among them.Input: N = 4, K = 6
Output: -1
Explanation: No such permutation exists which satisfies the above condition.
Approach: To solve the problem follow the below idea:
The idea is to first store K-1 numbers, starting with K, in descending order, at even indices of the array, and then store the remaining numbers in ascending order at odd indices of the array. Finally, any remaining indices are filled with the natural sequence of numbers.
Below are the steps for the above approach:
1 4 2 3 5 6
Time Complexity: O(N)
Auxiliary Space: O(N)