Given two integers N and K and a range [L, R], the task is to build an array whose elements are unique and in the range [L, R] and the median of the array is K.
Examples:
Input: N = 6, K = -1, L = -5, R = 5
Output: -4 -3 -2 0 1 2
Explanation: Median = (-2 + 0)/2 = -1 which is equal to K.Input: N = 5, K = 4, L = 3, R = 8
Output: -1
Approach: The problem can be solved using the following mathematical idea:
- If the array is of odd length the median is the (N/2 + 1)th element after sorting.
- Otherwise, the median will be the average of (N/2) anf (N/2 + 1)th elements.
So the optimal way is to make an array such that the minimum value and the maximum value are as close to the median as possible.
This can be done by simply keeping the difference between the elements as 1.
Therefore the minimum element of the array wll be (K – N/2) and the maximum element will be (K + N/2).Note: In case of N being even K is the average of two middle elements. So those two elements have a difference of 2 between them and K will not be present in the array.
Follow the steps mentioned below to implement the observation:
- Find the possible minimum and maximum values of the array.
- If either L is greater than the minimum or R is less than the maximum then the array cannot be constructed.
- Otherwise, fix the minimum and generate all the elements by maintaining a gap of 1 between adjacent elements.
- In the case of N being even, the gap between the middle two elements will be 2.
- Return the generated array as the answer.
Below is the implementation of the above approach:
C++
|
-4 -3 -2 0 1 2
Time Complexity: O(N)
Auxiliary Space: O(N)