Generate Array with elements in given range and median as K

View Discussion

Improve Article

Save Article

Like Article

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++

  

#include <bits/stdc++.h>

using namespace std;

  

vector<int> constructArray(int N, int K, int L, int R)

{

    vector<int> ans;

    if (L > (K - (N / 2)) || R < (K + (N / 2)))

        ans.push_back(-1);

    else if (N & 1)

        for (int i = K - (N / 2);

             i <= K + (N / 2); i++)

            ans.push_back(i);

    else

        for (int i = K - (N / 2);

             i <= K + (N / 2); i++)

            if (i != K)

                ans.push_back(i);

    return ans;

}

  

int main()

{

    int N = 6, K = -1;

    int L = -5, R = 5;

  

    

    vector<int> ans

        = constructArray(N, K, L, R);

    for (int x : ans)

        cout << x << " ";

    return 0;

}

Output

-4 -3 -2 0 1 2 

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