Count distinct median possible for an Array using given ranges of elements
Last Updated :
24 Mar, 2023
Given an array of pairs arr[] which denotes the ranges of the elements of an array, the task is to count the distinct median of every possible array using these ranges.
Examples:
Input: arr[] = {{1, 2}, {2, 3}}
Output: 3
Explanation:
=> If x1 = 1 and x2 = 2, Median is 1.5
=> If x1 = 1 and x2 = 3, Median is 2
=> If x1 = 2 and x2 = 2, Median is 2
=> If x1 = 2 and x2 = 3, Median is 2.5
Hence the number of distinct medians are {1.5, 2, 2.5} i.e, 3
Input: arr[] = {{100, 100}, {10, 10000}, {1, 109}}
Output: 9991
Naive Approach: A simple solution is to try for all possible values of the array and find the median of all those elements and count the distinct median of the array.
Time Complexity:
O(k^{N})
, where K is the possible values of range.
Efficient Approach: The idea is to find the median of the starting range and end ranges of the elements of the array, then the difference of this median will denote the distinct median of every possible array. Below is the illustration of the approach:
- Store all the starting range values in an array.
- Sort the array of starting range and find the median of the array.
- For odd length of the array - median = A[n/2]
- For even length of the array - median =
\frac{A[n/2] + A[n/2 - 1]}{2}
- Store all the end range values in an array.
- Sort the array of the ending range and find the median of the array
- For odd length of the array, median = B[n/2]
- For even N, median =
\frac{B[n/2] + B[n/2 - 1]}{2}
- When the length of the array is odd, Then all the integral values are differing by 1 in the range of the starting range median to the ending range median.
- Hence, Count of the distinct median will be the difference of the median of the starting ranges and median of the ending ranges.
- When the length of the array is even, Then all the integral values are differing by 0.5, in the range of the starting range median to the ending range median.
- All values differing by 0.5 in range [l, r] is the same as all values differing by 1 in range[2 * l, 2 * r]
- Hence, Count of the distinct median is
2 * right median - 2 * left median + 1
Below is the implementation of the above approach:
C++
// C++ implementation to Count the
// number of distinct medians of an array
// where each array elements
// are given by a range
#include <bits/stdc++.h>
using namespace std;
#define int long long int
// Function to Count the
// number of distinct medians of an array
// where each array elements
// are given by a range
void solve(int n,
const vector<pair<int, int> >& vec)
{
vector<int> a, b;
// Loop to store the starting
// and end range in the array
for (auto pr : vec) {
a.push_back(pr.first);
b.push_back(pr.second);
}
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int left, right, ans;
// Condition to check if the
// length of the array is odd
if ((n & 1)) {
left = a[n / 2];
right = b[n / 2];
ans = right - left + 1;
}
else {
left = (a[n / 2] + a[n / 2 - 1]);
right = (b[n / 2] + b[n / 2 - 1]);
ans = right - left + 1;
}
cout << ans << endl;
}
// Driver Code
signed main()
{
int N = 3;
vector<pair<int, int> > vec =
{ { 100, 100 }, { 10, 10000 },
{ 1, 1000000000 } };
// Function Call
solve(N, vec);
return 0;
}
Java
// Java implementation to count the
// number of distinct medians of an
// array where each array elements
// are given by a range
import java.util.*;
import java.awt.*;
class GFG{
// Function to count the number
// of distinct medians of an array
// where each array elements are
// given by a range
static void solve(int n, ArrayList<Point> vec)
{
ArrayList<Integer> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();
// Loop to store the starting
// and end range in the array
for(Point pr : vec)
{
a.add(pr.x);
b.add(pr.y);
}
Collections.sort(a);
Collections.sort(b);
int left, right, ans;
// Condition to check if the
// length of the array is odd
if ((n & 1) != 0)
{
left = a.get(n / 2);
right = b.get(n / 2);
ans = right - left + 1;
}
else
{
left = (a.get(n / 2) +
a.get(n / 2 - 1));
right = (b.get(n / 2) +
b.get(n / 2 - 1));
ans = right - left + 1;
}
System.out.println(ans);
}
// Driver Code
public static void main(String[] args)
{
int N = 3;
ArrayList<Point> vec = new ArrayList<>();
vec.add(new Point(100, 100));
vec.add(new Point(10, 10000));
vec.add(new Point(1, 1000000000));
// Function call
solve(N, vec);
}
}
// This code is contributed by jrishabh99
Python3
# Python3 implementation to count the
# number of distinct medians of an array
# where each array elements
# are given by a range
# Function to count the number of
# distinct medians of an array
# where each array elements
# are given by a range
def solve(n, vec):
a = []
b = []
# Loop to store the starting
# and end range in the array
for pr in vec :
a.append(pr[0])
b.append(pr[1])
a.sort()
b.sort()
# Condition to check if the
# length of the array is odd
if ((n & 1)):
left = a[n // 2]
right = b[n // 2]
ans = right - left + 1
else:
left = (a[n // 2] + a[n // 2 - 1])
right = (b[n // 2] + b[n // 2 - 1])
ans = right - left + 1
print(ans)
# Driver Code
if __name__ == "__main__":
N = 3
vec = [ (100, 100), (10, 10000),
(1, 1000000000) ]
# Function Call
solve(N, vec)
# This code is contributed by chitranayal
C#
// C# implementation to count the
// number of distinct medians of
// an array where each array elements
// are given by a range
using System;
using System.Collections;
using System.Collections.Generic;
public class Point
{
public int x, y;
public Point(int xx, int yy)
{
x = xx;
y = yy;
}
}
class GFG{
// Function to count the number
// of distinct medians of an array
// where each array elements are
// given by a range
static void solve(int n, ArrayList vec)
{
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
// Loop to store the starting
// and end range in the array
foreach(Point pr in vec)
{
a.Add(pr.x);
b.Add(pr.y);
}
a.Sort();
b.Sort();
int left, right, ans;
// Condition to check if the
// length of the array is odd
if ((n & 1) != 0)
{
left = (int)a[n / 2];
right = (int)b[n / 2];
ans = right - left + 1;
}
else
{
left = ((int)a[n / 2] +
(int)a[n / 2 - 1]);
right = ((int)b[n / 2] +
(int)b[n / 2 - 1]);
ans = right - left + 1;
}
Console.WriteLine(ans);
}
// Driver code
static public void Main()
{
int N = 3;
ArrayList vec = new ArrayList();
vec.Add(new Point(100, 100));
vec.Add(new Point(10, 10000));
vec.Add(new Point(1, 1000000000));
// Function call
solve(N, vec);
}
}
// This code is contributed by offbeat
JavaScript
<script>
// Javascript implementation to count the
// number of distinct medians of an
// array where each array elements
// are given by a range
// Function to count the number
// of distinct medians of an array
// where each array elements are
// given by a range
function solve(n,vec)
{
let a = [];
let b = [];
// Loop to store the starting
// and end range in the array
for(let pr=0;pr<vec.length;pr++)
{
a.push(vec[pr][0]);
b.push(vec[pr][1]);
}
a.sort(function(c,d){return c-d;});
b.sort(function(c,d){return c-d;});
let left, right, ans;
// Condition to check if the
// length of the array is odd
if ((n & 1) != 0)
{
left = a[(Math.floor(n / 2))];
right = b[(Math.floor(n / 2))];
ans = right - left + 1;
}
else
{
left = (a[(Math.floor(n / 2))] +
a[(Math.floor(n / 2) - 1)]);
right = (b[(Math.floor(n / 2))] +
b[(Math.floor(n / 2) - 1)]);
ans = right - left + 1;
}
document.write(ans);
}
// Driver Code
let N = 3;
let vec=[];
vec.push([100,100]);
vec.push([10, 10000]);
vec.push([1, 1000000000]);
// Function call
solve(N, vec);
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(nlogn), time used for sorting vectors a and b
Auxiliary Space: O(n), as extra space of size n is used to create vectors.
Similar Reads
Count of elements in X axis for given Q ranges Given a 2D array arr[][] where each array element denotes a point in the X axis and the number of elements on that point. A query array queries[] of size Q is given where each element is of type {l, r}. The task is to find the count of elements in the given range for each query. Examples: Input: arr
10 min read
Queries for counts of array values in a given range Given an unsorted array of integers and a set of m queries, where each query consists of two integers x and y, the task is to determine the number of elements in the array that lie within the range [x, y] (inclusive) for each query.Examples: Input: arr = [1, 3, 4, 9, 10, 3], queries = [[1, 4], [9, 1
15+ min read
Generate Array with elements in given range and median as K 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 = 5Output: -4 -3 -2 0 1 2Explanation: Median = (-2 + 0)/2 = -1 which is equal to K. Input: N = 5,
6 min read
Change in Median of given array after deleting given elements Given two arrays arr1[] and arr2[]. The array arr1[] is sorted. The task is to print the change in the median after removing each element from array arr2[] one by one. Note: The array arr2[] has only those elements that are present in array arr1[]. Examples: Input: arr1[] = {2, 4, 6, 8, 10}, arr2[]
7 min read
Queries for count of elements not present in range Given an integer N which represents the total number of IDs present, a 2D array arr of size Mx2, where arr[i] = [ID, score] and 1D array query of size Q. We can assign multiple scores to a single ID. For each query q[i] where 0 <= i < Q, find the number of IDs who don't have any scores within
10 min read