Open In App

Find Median for each Array element by excluding the index at which Median is calculated

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A[] of N integers where N is even, . the task is to generate an array of medians where the median of the array is calculated by taking the median of array A[] excluding A[i]-th element.

Examples:

Input N = 4, A = [2, 4, 4, 3]
Output: [4, 3, 3, 4]
Explanation: Median after removing A[0]: New sorted array will be [3, 4, 4]. Median = 4. 
Median after removing A[1]: New sorted array will be [2, 3, 4]. Median = 3. 
Median after removing A[0]: New sorted array will be [2, 3, 4]. Median = 3. 
Median after removing A[0]: New sorted array will be [2, 4, 4]. Median = 4.

Input: N = 6, A = [5, 5, 4, 4, 3, 3]
Output: [4, 4, 4, 4, 4, 4]

 

Naive Approach: For each i in the range [0, N) remove the current element and sort the remaining array then calculate the median of the new array.

Implementation:-

C++




// C++ Program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return Median array after
// excluding each individual element
void findMedianExcludedArray(int A[], int N)
{
      //iterating over array A
    for (int i = 0; i < N; i++) {
        
          //Taking pointer to 0 for array B
        int j=0;
        
          //Taking array B of size N-1
          int B[N-1]; 
        
          //Taking all elements of A into B except element at index i
          for(int k=0;k<N;k++)
        {
              if(k==i)continue;
              B[j]=A[k];
              j++;
        }
            
          //sorting B array
          sort(B,B+N-1);
        
          //printing the median
          cout<<B[(N-1)/2]<<" ";
    }
  
}
  
// Driver Code
int main()
{
    int N = 4;
    int A[] = { 2, 4, 4, 3 };
    findMedianExcludedArray(A, N);
}


Java




// Java Program for the above approach
import java.util.Arrays;
  
public class GFG 
{
    // Function to return Median array after
    // excluding each individual element
    static void findMedianExcludedArray(int A[], int N)
    {
        // iterating over array A
        for (int i = 0; i < N; i++) 
        {
            // Taking pointer to 0 for array B
            int j=0;
            
            // Taking array B of size N-1
            int B[] = new int[N-1]; 
            
            // Taking all elements of A into B except element at index i
            for(int k=0;k<N;k++)
            {
                if(k==i)continue;
                B[j]=A[k];
                j++;
            }
              
            // sorting B array
            Arrays.sort(B);
            
            // printing the median
            System.out.print(B[(N-1)/2]+" ");
        }
    }
    
    // Driver Code
    public static void main(String args[])
    {
        int N = 4;
        int A[] = { 2, 4, 4, 3 };
        findMedianExcludedArray(A, N);
    }
}


Python3




# Python Program for the above approach
  
  
# Function to return Median array after
# excluding each individual element
def findMedianExcludedArray(A, N):
    
      # iterating over array A
    for i in range(N):
        
          # Taking pointer to 0 for array B
        j = 0
          
        # Taking array B of size N-1
        B = [0] * (N-1)
          
        # Taking all elements of A into B except element at index i
        for k in range(N):
            if k == i:
                continue
            B[j] = A[k]
            j += 1
              
        # sorting array B
        B.sort()
          
        # printing the median
        print(B[(N-1)//2], end=" ")
  
#driver code
N = 4
A = [2, 4, 4, 3]
findMedianExcludedArray(A, N)


C#




// C# Program for the above approach
using System;
  
public static class GFG 
{
    // Function to return Median array after
    // excluding each individual element
    static void findMedianExcludedArray(int[] A, int N)
    {
        // iterating over array A
        for (int i = 0; i < N; i++) 
        {
            // Taking pointer to 0 for array B
            int j=0;
            
            // Taking array B of size N-1
            int[] B = new int[N-1]; 
            
            // Taking all elements of A into B except element at index i
            for(int k=0;k<N;k++)
            {
                if(k==i)continue;
                B[j]=A[k];
                j++;
            }
              
            // sorting B array
            Array.Sort(B);
            
            // printing the median
            Console.Write(B[(N-1)/2]+" ");
        }
    }
    
    // Driver Code
    public static void Main()
    {
        int N = 4;
        int[] A = { 2, 4, 4, 3 };
        findMedianExcludedArray(A, N);
    }
}


Javascript




// Function to return Median array after
// excluding each individual element
function findMedianExcludedArray(A, N) {
    //iterating over array A
    for (let i = 0; i < N; i++) {
        //Taking pointer to 0 for array B
        let j = 0;
        //Taking array B of size N-1
        let B = new Array(N - 1);
        //Taking all elements of A into B except element at index i
        for (let k = 0; k < N; k++) {
            if (k == i) continue;
            B[j] = A[k];
            j++;
        }
        //sorting B array
        B.sort(function(a, b) { return a - b });
        //printing the median
          
        process.stdout.write(B[(Math.floor((N - 1) / 2))] + " ");
    }
}
  
// Driver Code
let N = 4;
let A = [2, 4, 4, 3];
findMedianExcludedArray(A, N);


Output

4 3 3 4 

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

Efficient Approach: As N is even, there are two central elements in the current array which can be the median of the current array. On removing any one of the elements then there will be an odd number of elements and one of the center elements will always be the answer. Let us denote the two center values be L and R. There are 2 possible cases – When the current A[i] <=L then R will be the final median of the array. Otherwise, when current A[i] >= R then L will be the final median of the array. Follow the steps below to solve the problem:

  • Initialize an array B[] to store the original positions of the elements in the array.
  • Iterate over the range [0, N) using the variable i and perform the following steps:
    • Store A[i] in the new array B[i].
  • Sort the array A[] to find the central elements.
  • Iterate over the range [0, N) using the variable i and perform the following steps:
    • If B[i] is less than equal to L, then R will be the median of the array excluding A[i].
    • Else, L will be the required median.

Below is the implementation of the above approach.

C++




// C++ Program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return Median array after
// excluding each individual element
int findMedianExcludedArray(int A[], int N)
{
  
    // Store the original array in another
    // array to store the sorted version
    // and the original position of the array
    // element is also important
    int B[N];
    for (int i = 0; i < N; i++) {
        B[i] = A[i];
    }
  
    // Sort the original array
    sort(A, A + N);
  
    // Stores the left median
    int L = A[N / 2 - 1];
  
    // Stores the right median
    int R = A[N / 2];
  
    // Iterate over the range
    for (int i = 0; i < N; i++) {
  
        // If A[i] is less than equal to L,
        // then after removing it, R will become
        // the central element, otherwise L
        if (B[i] <= L) {
            cout << R;
        }
        else {
            cout << L;
        }
        if (i != N - 1) {
            cout << ", ";
        }
    }
  
    return 0;
}
  
// Driver Code
int main()
{
    int N = 4;
    int A[] = { 2, 4, 4, 3 };
    findMedianExcludedArray(A, N);
}


Java




// Java code for above approach
import java.util.*;
  
class GFG{
  
// Function to return Median array after
// excluding each individual element
static int findMedianExcludedArray(int[] A, int N)
{
  
    // Store the original array in another
    // array to store the sorted version
    // and the original position of the array
    // element is also important
    int[] B = new int[N];
    for (int i = 0; i < N; i++) {
        B[i] = A[i];
    }
  
    // Sort the original array
    Arrays.sort(A);
  
    // Stores the left median
    int L = A[N / 2 - 1];
  
    // Stores the right median
    int R = A[N / 2];
  
    // Iterate over the range
    for (int i = 0; i < N; i++) {
  
        // If A[i] is less than equal to L,
        // then after removing it, R will become
        // the central element, otherwise L
        if (B[i] <= L) {
             System.out.print(R);
        }
        else {
             System.out.print(L);
        }
        if (i != N - 1) {
             System.out.print(", ");
        }
    }
  
    return 0;
}
  
// Driver Code
public static void main(String[] args)
{
    int N = 4;
    int[] A = { 2, 4, 4, 3 };
    findMedianExcludedArray(A, N);
}
}
  
// This code is contributed by target_2.


Python3




# Function to return Median array after
# excluding each individual element
def findMedianExcludedArray(A, N):
    
    # Store the original array in another
    # array to store the sorted version
    # and the original position of the array
    # element is also important
    B = []
    for i in range(N):
        B.append(A[i])
          
        # sort the original array
    A.sort()
      
    # Stores the left median
    L = A[N//2 - 1]
      
    # Stores the right median
    R = A[N//2]
      
     # Iterate over the range
    for i in range(N):
        
         # If A[i] is less than equal to L,
        # then after removing it, R will become
        # the central element, otherwise L
        if B[i] <= L:
            print(R, end="")
        else:
            print(L, end="")
        if i != N-1:
            print(", ", end="")
  
# Driver code
N = 4
A = [2, 4, 4, 3]
findMedianExcludedArray(A, N)
  
# This code is contributed by Parth Manchanda


C#




// C# program for above approach
using System;
  
class GFG{
  
// Function to return Median array after
// excluding each individual element
static int findMedianExcludedArray(int[] A, int N)
{
  
    // Store the original array in another
    // array to store the sorted version
    // and the original position of the array
    // element is also important
    int[] B = new int[N];
    for (int i = 0; i < N; i++) {
        B[i] = A[i];
    }
  
    // Sort the original array
    Array.Sort(A);
  
    // Stores the left median
    int L = A[N / 2 - 1];
  
    // Stores the right median
    int R = A[N / 2];
  
    // Iterate over the range
    for (int i = 0; i < N; i++) {
  
        // If A[i] is less than equal to L,
        // then after removing it, R will become
        // the central element, otherwise L
        if (B[i] <= L) {
             Console.Write(R);
        }
        else {
             Console.Write(L);
        }
        if (i != N - 1) {
             Console.Write(", ");
        }
    }
  
    return 0;
}
  
// Driver Code
static void Main()
{
    int N = 4;
    int[] A = { 2, 4, 4, 3 };
    findMedianExcludedArray(A, N);
}
}
  
// This code is contributed by sanjoy_62.


Javascript




<script>
  
// JavaScript program for the above approach
  
// Function to return Median array after
// excluding each individual element
function findMedianExcludedArray(A, N)
{
  
    // Store the original array in another
    // array to store the sorted version
    // and the original position of the array
    // element is also important
    let B = new Array(N);
    for (let i = 0; i < N; i++) {
        B[i] = A[i];
    }
  
    // Sort the original array
    A.sort();
  
    // Stores the left median
    let L = A[N / 2 - 1];
  
    // Stores the right median
    let R = A[N / 2];
  
    // Iterate over the range
    for (let i = 0; i < N; i++) {
  
        // If A[i] is less than equal to L,
        // then after removing it, R will become
        // the central element, otherwise L
        if (B[i] <= L) {
             document.write(R);
        }
        else {
             document.write(L);
        }
        if (i != N - 1) {
             document.write(", ");
        }
    }
  
    return 0;
}
  
// Driver Code
  
    let N = 4;
    let A = [ 2, 4, 4, 3 ];
    findMedianExcludedArray(A, N);
  
// This code is contributed by splevel62.
</script>


Output: 

4, 3, 3, 4

 

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



Last Updated : 24 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads