Find Median of the Array formed from given frequencies of elements
Last Updated :
14 Mar, 2023
Given an array A[] containing N elements of an array and their frequency in that array (say arr[]), the task is to find the median of the array whose elements and frequency are given.
Note: Median of an array is the element at the middle of the sorted array
Examples:
Input: A[] = { {1, 2}, {4, 2}, {5, 1} }
Output: 4
Explanation: The array whose elements are given is {1, 1, 4, 4, 5}.
Therefore, the median of the array will be 4.
Input: A[] = { {3, 4}, {2, 3}, {9, 2} }
Output: 3
Explanation: The newly created array will be {2, 2, 2, 3, 3, 3, 3, 9, 9}.
Therefore the median of the array will be 3.
Naive Approach: The basic approach is to create the array and then sort the array and find the middle element of that array.
C++
#include<bits/stdc++.h>
using namespace std;
int findMedian(vector<vector< int > > a, int n)
{
vector< int > v;
for ( int i=0;i<a.size();i++)
{
for ( int j=0;j<a[0].size();j++)
v.push_back(a[i][0]);
}
sort(v.begin(),v.end());
return v[v.size()/2];
}
int main() {
vector<vector< int > > A;
A = { { 1, 2 }, { 4, 2 }, { 5, 1 } };
int N = A.size();
cout << findMedian(A, N);
return 0;
}
|
Java
import java.util.Arrays;
import java.util.Vector;
public class Main {
static int findMedian(Vector< int []> a, int n)
{
Vector<Integer> v = new Vector<>();
for ( int i = 0 ; i < a.size(); i++) {
for ( int j = 0 ; j < a.get( 0 ).length; j++)
v.add(a.get(i)[ 0 ]);
}
Integer[] arr = v.toArray( new Integer[v.size()]);
Arrays.sort(arr);
return arr[arr.length / 2 ];
}
public static void main(String[] args)
{
Vector< int []> A = new Vector<>();
A.add( new int [] { 1 , 2 });
A.add( new int [] { 4 , 2 });
A.add( new int [] { 5 , 1 });
int N = A.size();
System.out.println(findMedian(A, N));
}
}
|
Python3
def findMedian(a, n):
v = []
for i in range ( len (a)):
for j in range ( len (a[ 0 ])):
v.append(a[i][ 0 ])
v.sort()
return v[ len (v) / / 2 ]
if __name__ = = "__main__" :
A = [[ 1 , 2 ], [ 4 , 2 ], [ 5 , 1 ]]
N = len (A)
print (findMedian(A, N))
|
Javascript
function findMedian(arr, n) {
let v = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[0].length; j++)
v.push(arr[i][0]);
}
v = v.sort( function (a, b){ return a-b});
return v[v.length / 2];
}
let A = [[1, 2], [4, 2], [5, 1]];
let N = A.length;
console.log(findMedian(A, N));
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static int FindMedian(List< int []> a, int n)
{
List< int > v = new List< int >();
for ( int i = 0; i < a.Count; i++) {
for ( int j = 0; j < a[0].Length; j++)
v.Add(a[i][0]);
}
int [] arr = v.ToArray();
Array.Sort(arr);
return arr[arr.Length / 2];
}
static void Main( string [] args)
{
List< int []> A = new List< int []>();
A.Add( new int [] { 1, 2 });
A.Add( new int [] { 4, 2 });
A.Add( new int [] { 5, 1 });
int N = A.Count;
Console.WriteLine(FindMedian(A, N));
}
}
|
Time Complexity: O(M * log M) where M is the sum of the frequencies of all elements given in A[].
Auxiliary Space: O(M)
Efficient approach: As the sum of frequencies of the elements present in A[] can be very large it is not feasible to build an array. This can be solved efficiently based on the following idea:
Sort the array A[] based on the value of elements. Now calculate the total number of elements that will be in the array formed from these elements (say M). The element at M/2 th position is the median.
So iterate from the minimum elements and with the help of their frequencies find out the element and M/2 th position.
Follow the below steps to implement the above idea:
- Insert all the elements in a map with the elements as the key and their frequency as value (a map is sorted based on the value of the key. Therefore it satisfies the need of sorting).
- Count total elements that will be in the array.
- Iterate from the minimum elements and check if the total elements till the current value is the same as M/2:
- If it is same, then the current element is the required median.
- Otherwise, increase the total number of elements till now.
- Return the median.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int findMedian(vector<vector< int > > a, int n)
{
map< int , int > m;
int totalsize = 0;
for ( int i = 0; i < n; i++) {
int val = a[i][0];
int time = a[i][1];
m[val] += time ;
totalsize += time ;
}
int meidanpos = totalsize / 2;
long long pos = 0;
for ( auto it : m) {
if (pos + it.second > meidanpos) {
return it.first;
}
else {
pos += it.second;
}
}
}
int main()
{
vector<vector< int > > A;
A = { { 1, 2 }, { 4, 2 }, { 5, 1 } };
int N = A.size();
cout << findMedian(A, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
public static int findMedian( int a[][], int n)
{
TreeMap<Integer, Integer> m
= new TreeMap<Integer, Integer>();
int totalsize = 0 ;
for ( int i = 0 ; i < n; i++) {
int val = a[i][ 0 ];
int time = a[i][ 1 ];
if (m.get(val) != null )
m.put(val, m.get(val) + time);
else
m.put(val, time);
totalsize += time;
}
int meidanpos = totalsize / 2 ;
long pos = 0 ;
for (Map.Entry<Integer, Integer> it :
m.entrySet()) {
if (pos + it.getValue() > meidanpos) {
return it.getKey();
}
else {
pos += it.getValue();
}
}
return 0 ;
}
public static void main(String[] args)
{
int A[][] = { { 1 , 2 }, { 4 , 2 }, { 5 , 1 } };
int N = A.length;
System.out.print(findMedian(A, N));
}
}
|
Python3
def findMedian(a, n):
m = dict ()
totalsize = 0
for i in range (n):
val = a[i][ 0 ]
time = a[i][ 1 ]
if val in m:
m[val] + = time
else :
m[val] = time
totalsize + = time
medianpos = totalsize / / 2
pos = 0
for it in m.items():
if pos + it[ 1 ] > medianpos:
return it[ 0 ]
else :
pos + = it[ 1 ]
A = [[ 1 , 2 ], [ 4 , 2 ], [ 5 , 1 ]]
N = len (A)
print (findMedian(A, N))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int findMedian( int [,] a, int n)
{
Dictionary< int , int > m = new Dictionary< int , int >();
int totalsize = 0;
for ( int i = 0; i < n; i++) {
int val = a[i,0];
int time = a[i,1];
if (m.ContainsKey(val))
m[val]=m[val] + time;
else
m[val]=time;
totalsize += time;
}
int meidanpos = totalsize / 2;
long pos = 0;
foreach (KeyValuePair< int , int > it in m)
{
if (pos + it.Value > meidanpos) {
return it.Key;
}
else {
pos += it.Value;
}
}
return 0;
}
public static void Main()
{
int [,] A = { { 1, 2 }, { 4, 2 }, { 5, 1 } };
int N = A.GetLength(0);;
Console.Write(findMedian(A, N));
}
}
|
Javascript
<script>
function findMedian(a, n){
let m = new Map()
let totalsize = 0
for (let i = 0; i < n; i++){
let val = a[i][0]
let time = a[i][1]
if (m.has(val))
m.set(val,m.get(val)+time)
else
m.set(val,time)
totalsize += time
}
let medianpos = Math.floor(totalsize / 2)
let pos = 0
for (let [it,it2] of m)
{
if (pos + it2 > medianpos)
return it
else
pos += it2
}
}
let A = [[1, 2], [4, 2], [5, 1]]
let N = A.length
document.write(findMedian(A, N))
</script>
|
Time Complexity: O(N * logN)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...