Given two integers N and Ok and a spread [L, R], the duty is to construct an array whose parts are distinctive and within the vary [L, R] and the median of the array is Ok.
Enter: N = 6, Ok = -1, L = -5, R = 5
Output: -4 -3 -2 0 1 2
Rationalization: Median = (-2 + 0)/2 = -1 which is the same as Ok.
Enter: N = 5, Ok = 4, L = 3, R = 8
Method: The issue will be solved utilizing the next mathematical thought:
- If the array is of strange size the median is the (N/2 + 1)th component after sorting.
- In any other case, the median would be the common of (N/2) anf (N/2 + 1)th parts.
So the optimum means is to make an array such that the minimal worth and the utmost worth are as near the median as potential.
This may be executed by merely conserving the distinction between the weather as 1.
Due to this fact the minimal component of the array wll be (Ok – N/2) and the utmost component might be (Ok + N/2).
Be aware: In case of N being even Ok is the common of two center parts. So these two parts have a distinction of two between them and Ok won’t be current within the array.
Comply with the steps talked about beneath to implement the commentary:
- Discover the potential minimal and most values of the array.
- If both L is larger than the minimal or R is lower than the utmost then the array can’t be constructed.
- In any other case, repair the minimal and generate all the weather by sustaining a spot of 1 between adjoining parts.
- Within the case of N being even, the hole between the center two parts might be 2.
- Return the generated array as the reply.
Under is the implementation of the above strategy:
Time Complexity: O(N)
Auxiliary House: O(N)