Given an array of n integers in non-decreasing order. Find the number of occurrences of the most frequent value within a given range.
Examples:
Input : arr[] = {-5, -5, 2, 2, 2, 2, 3, 7, 7, 7}
Query 1: start = 0, end = 9
Query 2: start = 4, end = 9
Output : 4
3
Explanation:
Query 1: '2' occurred the most number of times
with a frequency of 4 within given range.
Query 2: '7' occurred the most number of times
with a frequency of 3 within given range.
Segment Trees can be used to solve this problem efficiently.
Refer here for the implementation of segment trees
The key idea behind this problem is that the given array is in non-decreasing order which means that all occurrences of a number are consecutively placed in the array as the array is in sorted order.
A segment tree can be constructed where each node would store the maximum count of its respective range [i, j]. For that we will build the frequency array and call RMQ (Range Maximum Query) on this array. For e.g.
arr[] = {-5, -5, 2, 2, 2, 2, 3, 7, 7, 7}
freq_arr[] = {2, 2, 4, 4, 4, 4, 1, 3, 3, 3}
where, freq_arr[i] = frequency(arr[i])
Now there are two cases to be considered,
Case 1: The value of the numbers at index i and j for the given range are same, i.e. arr[i] = arr[j].
Solving this case is very easy. Since arr[i] = arr[j], all numbers between these indices are same (since the array is non-decreasing). Hence answer for this case is simply count of all numbers between i and j (inclusive both) i.e. (j – i + 1)
For e.g.
arr[] = {-5, -5, 2, 2, 2, 2, 3, 7, 7, 7}
if the given query range is [3, 5], answer would
be (5 - 3 + 1) = 3, as 2 occurs 3 times within
given range
Case 2: The value of the numbers at index i and j for the given range are different, i.e. arr[i] != arr[j]
If arr[i] != arr[j], then there exists an index k where arr[i] = arr[k] and arr[i] != arr[k + 1]. This may be a case of partial overlap where some occurrences of a particular number lie in the leftmost part of the given range and some lie just before range starts. Here simply calling RMQ would result into an incorrect answer.
For e.g.
arr[] = {-5, -5, 2, 2, 2, 2, 3, 7, 7, 7}
freq_arr[] = {2, 2, 4, 4, 4, 4, 1, 3, 3, 3}
if the given query is [4, 9], calling RMQ on
freq_arr[] will give us 4 as answer which
is incorrect as some occurrences of 2 are
lying outside the range. Correct answer
is 3.
Similar situation can happen at the rightmost part of the given range where some occurrences of a particular number lies inside the range and some lies just after the range ends.
Hence for this case, inside the given range we have to count the leftmost same numbers upto some index say i and rightmost same numbers from index say j to the end of the range. And then calling RMQ (Range Maximum Query) between indices i and j and taking maximum of all these three.
For e.g.
arr[] = {-5, -5, 2, 2, 2, 2, 3, 7, 7, 7}
freq_arr[] = {2, 2, 4, 4, 4, 4, 1, 3, 3, 3}
if the given query is [4, 7], counting leftmost
same numbers i.e 2 which occurs 2 times inside
the range and rightmost same numbers i.e. 3
which occur only 1 time and RMQ on [6, 6] is
1. Hence maximum would be 2.
Below is the implementation of the above approach
C++
#include <bits/stdc++.h>
using namespace std;
int getMid( int s, int e) { return s + (e - s) / 2; }
int RMQUtil( int * st, int ss, int se, int qs, int qe,
int index)
{
if (qs <= ss && qe >= se)
return st[index];
if (se < qs || ss > qe)
return 0;
int mid = getMid(ss, se);
return max(RMQUtil(st, ss, mid, qs, qe, 2 * index + 1),
RMQUtil(st, mid + 1, se, qs, qe, 2 * index + 2));
}
int RMQ( int * st, int n, int qs, int qe)
{
if (qs < 0 || qe > n - 1 || qs > qe) {
printf ( "Invalid Input" );
return -1;
}
return RMQUtil(st, 0, n - 1, qs, qe, 0);
}
int constructSTUtil( int arr[], int ss, int se, int * st,
int si)
{
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
int mid = getMid(ss, se);
st[si] = max(constructSTUtil(arr, ss, mid, st, si * 2 + 1),
constructSTUtil(arr, mid + 1, se, st, si * 2 + 2));
return st[si];
}
int * constructST( int arr[], int n)
{
int x = ( int )( ceil (log2(n)));
int max_size = 2 * ( int ) pow (2, x) - 1;
int * st = new int [max_size];
constructSTUtil(arr, 0, n - 1, st, 0);
return st;
}
int maximumOccurrence( int arr[], int n, int qs, int qe)
{
int freq_arr[n + 1];
unordered_map< int , int > cnt;
for ( int i = 0; i < n; i++)
cnt[arr[i]]++;
for ( int i = 0; i < n; i++)
freq_arr[i] = cnt[arr[i]];
int * st = constructST(freq_arr, n);
int maxOcc;
if (arr[qs] == arr[qe])
maxOcc = (qe - qs + 1);
else {
int leftmost_same = 0, righmost_same = 0;
while (qs > 0 && qs <= qe && arr[qs] == arr[qs - 1]) {
qs++;
leftmost_same++;
}
while (qe >= qs && qe < n - 1 && arr[qe] == arr[qe + 1]) {
qe--;
righmost_same++;
}
maxOcc = max({leftmost_same, righmost_same,
RMQ(st, n, qs, qe)});
}
return maxOcc;
}
int main()
{
int arr[] = { -5, -5, 2, 2, 2, 2, 3, 7, 7, 7 };
int n = sizeof (arr) / sizeof (arr[0]);
int qs = 0;
int qe = 9;
cout << "Maximum Occurrence in range is = "
<< maximumOccurrence(arr, n, qs, qe) << endl;
qs = 4;
qe = 9;
cout << "Maximum Occurrence in range is = "
<< maximumOccurrence(arr, n, qs, qe) << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.HashMap;
class GFG {
public static int getMid( int s, int e) {
return s + (e - s) / 2 ;
}
public static int RMQUtil( int [] st, int ss, int se, int qs, int qe,
int index) {
if (qs <= ss && qe >= se)
return st[index];
if (se < qs || ss > qe)
return 0 ;
int mid = getMid(ss, se);
return Math.max(RMQUtil(st, ss, mid, qs, qe, 2 * index + 1 ),
RMQUtil(st, mid + 1 , se, qs, qe, 2 * index + 2 ));
}
public static int RMQ( int [] st, int n, int qs, int qe) {
if (qs < 0 || qe > n - 1 || qs > qe) {
System.out.println( "Invalid Input" );
return - 1 ;
}
return RMQUtil(st, 0 , n - 1 , qs, qe, 0 );
}
public static int constructSTUtil( int arr[], int ss, int se, int [] st,
int si) {
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
int mid = getMid(ss, se);
st[si] = Math.max(constructSTUtil(arr, ss, mid, st, si * 2 + 1 ),
constructSTUtil(arr, mid + 1 , se, st, si * 2 + 2 ));
return st[si];
}
public static int [] constructST( int arr[], int n)
{
int x = ( int )(Math.ceil(Math.log(n) / Math.log( 2 )));
int max_size = 2 * ( int )Math.pow( 2 , x) - 1 ;
int [] st = new int [max_size];
constructSTUtil(arr, 0 , n - 1 , st, 0 );
return st;
}
public static int maximumOccurrence( int arr[], int n, int qs, int qe)
{
int freq_arr[] = new int [n + 1 ];
HashMap<Integer, Integer> cnt = new HashMap<>();
for ( int i = 0 ; i < n; i++)
cnt.put(arr[i], cnt.getOrDefault(arr[i], 0 ) + 1 );
for ( int i = 0 ; i < n; i++)
freq_arr[i] = cnt.get(arr[i]);
int [] st = constructST(freq_arr, n);
int maxOcc;
if (arr[qs] == arr[qe])
maxOcc = (qe - qs + 1 );
else {
int leftmost_same = 0 , righmost_same = 0 ;
while (qs > 0 && qs <= qe && arr[qs] == arr[qs - 1 ]) {
qs++;
leftmost_same++;
}
while (qe >= qs && qe < n - 1 && arr[qe] == arr[qe + 1 ]) {
qe--;
righmost_same++;
}
maxOcc = Math.max(Math.max(leftmost_same, righmost_same),
RMQ(st, n, qs, qe));
}
return maxOcc;
}
public static void main(String[] args) {
int [] arr = { - 5 , - 5 , 2 , 2 , 2 , 2 , 3 , 7 , 7 , 7 };
int n = arr.length;
int qs = 0 ;
int qe = 9 ;
System.out.println( "Maximum Occurrence in range is = " + maximumOccurrence(arr, n, qs, qe));
qs = 4 ;
qe = 9 ;
System.out.println( "Maximum Occurrence in range is = " + maximumOccurrence(arr, n, qs, qe));
}
}
|
Python3
from collections import defaultdict
import math
def getMid(s, e):
return s + (e - s) / / 2
def RMQUtil(st, ss, se, qs, qe, index):
if (qs < = ss and qe > = se):
return st[index]
if (se < qs or ss > qe):
return 0
mid = getMid(ss, se)
return max (RMQUtil(st, ss, mid, qs, qe, 2 * index + 1 ),
RMQUtil(st, mid + 1 , se, qs, qe, 2 * index + 2 ))
def RMQ(st, n, qs, qe):
if (qs < 0 or qe > n - 1 or qs > qe):
prf( "Invalid Input" )
return - 1
return RMQUtil(st, 0 , n - 1 , qs, qe, 0 )
def constructSTUtil(arr, ss, se, st,
si):
if (ss = = se):
st[si] = arr[ss]
return arr[ss]
mid = getMid(ss, se)
st[si] = max (constructSTUtil(arr, ss, mid, st, si * 2 + 1 ),
constructSTUtil(arr, mid + 1 , se, st, si * 2 + 2 ))
return st[si]
def constructST(arr, n):
x = (math.ceil(math.log2(n)))
max_size = 2 * pow ( 2 , x) - 1
st = [ 0 ] * max_size
constructSTUtil(arr, 0 , n - 1 , st, 0 )
return st
def maximumOccurrence(arr, n, qs, qe):
freq_arr = [ 0 ] * (n + 1 )
cnt = defaultdict( int )
for i in range (n):
cnt[arr[i]] + = 1
for i in range (n):
freq_arr[i] = cnt[arr[i]]
st = constructST(freq_arr, n)
maxOcc = 0
if (arr[qs] = = arr[qe]):
maxOcc = (qe - qs + 1 )
else :
leftmost_same = 0
righmost_same = 0
while (qs > 0 and qs < = qe and arr[qs] = = arr[qs - 1 ]):
qs + = 1
leftmost_same + = 1
while (qe > = qs and qe < n - 1 and arr[qe] = = arr[qe + 1 ]):
qe - = 1
righmost_same + = 1
maxOcc = max ([leftmost_same, righmost_same,
RMQ(st, n, qs, qe)])
return maxOcc
if __name__ = = "__main__" :
arr = [ - 5 , - 5 , 2 , 2 , 2 , 2 , 3 , 7 , 7 , 7 ]
n = len (arr)
qs = 0
qe = 9
print ( "Maximum Occurrence in range is = " ,
maximumOccurrence(arr, n, qs, qe))
qs = 4
qe = 9
print ( "Maximum Occurrence in range is = " ,
maximumOccurrence(arr, n, qs, qe))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static int GetMid( int s, int e)
{
return s + (e - s) / 2;
}
public static int RMQUtil( int [] st, int ss, int se, int qs, int qe,
int index)
{
if (qs <= ss && qe >= se)
return st[index];
if (se < qs || ss > qe)
return 0;
int mid = GetMid(ss, se);
return Math.Max(RMQUtil(st, ss, mid, qs, qe, 2 * index + 1),
RMQUtil(st, mid + 1, se, qs, qe, 2 * index + 2));
}
public static int RMQ( int [] st, int n, int qs, int qe)
{
if (qs < 0 || qe > n - 1 || qs > qe)
{
Console.WriteLine( "Invalid Input" );
return -1;
}
return RMQUtil(st, 0, n - 1, qs, qe, 0);
}
public static int ConstructSTUtil( int [] arr, int ss, int se, int [] st,
int si)
{
if (ss == se)
{
st[si] = arr[ss];
return arr[ss];
}
int mid = GetMid(ss, se);
st[si] = Math.Max(ConstructSTUtil(arr, ss, mid, st, si * 2 + 1),
ConstructSTUtil(arr, mid + 1, se, st, si * 2 + 2));
return st[si];
}
public static int [] ConstructST( int [] arr, int n)
{
int x = ( int )Math.Ceiling(Math.Log(n, 2));
int max_size = 2 * ( int )Math.Pow(2, x) - 1;
int [] st = new int [max_size];
ConstructSTUtil(arr, 0, n - 1, st, 0);
return st;
}
public static int maximumOccurrence( int [] arr, int n, int qs, int qe)
{
int [] freq_arr = new int [n + 1];
Dictionary< int , int > cnt = new Dictionary< int , int >();
for ( int i = 0; i < n; i++){
if (!cnt.ContainsKey(arr[i]))
{
cnt.Add(arr[i], 0);
}
cnt[arr[i]]++;
}
for ( int i = 0; i < n; i++)
freq_arr[i] = cnt[arr[i]];
int [] st = ConstructST(freq_arr, n);
int maxOcc;
if (arr[qs] == arr[qe])
maxOcc = (qe - qs + 1);
else {
int leftmost_same = 0, righmost_same = 0;
while (qs > 0 && qs <= qe && arr[qs] == arr[qs - 1]) {
qs++;
leftmost_same++;
}
while (qe >= qs && qe < n - 1 && arr[qe] == arr[qe + 1]) {
qe--;
righmost_same++;
}
maxOcc = Math.Max(Math.Max(leftmost_same, righmost_same),
RMQ(st, n, qs, qe));
}
return maxOcc;
}
static void Main() {
int [] arr = { -5, -5, 2, 2, 2, 2, 3, 7, 7, 7 };
int n = arr.Length;
int qs = 0;
int qe = 9;
Console.WriteLine( "Maximum Occurrence in range is = " + maximumOccurrence(arr, n, qs, qe));
qs = 4;
qe = 9;
Console.WriteLine( "Maximum Occurrence in range is = " + maximumOccurrence(arr, n, qs, qe));
}
}
|
Javascript
function getMid(s, e) {
return s + Math.floor((e - s) / 2);
}
function RMQUtil(st, ss, se, qs, qe, index) {
if (qs <= ss && qe >= se)
return st[index];
if (se < qs || ss > qe)
return 0;
let mid = getMid(ss, se);
return Math.max(RMQUtil(st, ss, mid, qs, qe, 2 * index + 1), RMQUtil(st, mid + 1, se, qs, qe, 2 * index + 2));
}
function RMQ(st, n, qs, qe) {
if (qs < 0 || qe > n - 1 || qs > qe) {
console.log( "Invalid Input" );
return -1;
}
return RMQUtil(st, 0, n - 1, qs, qe, 0);
}
function constructSTUtil(arr, ss, se, st, si) {
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
let mid = getMid(ss, se);
st[si] = Math.max(constructSTUtil(arr, ss, mid, st, si * 2 + 1), constructSTUtil(arr, mid + 1, se, st, si * 2 + 2));
return st[si];
}
function constructST(arr, n) {
let x = Math.ceil(Math.log2(n));
let max_size = 2 * Math.pow(2, x) - 1;
let st = new Array(max_size);
constructSTUtil(arr, 0, n - 1, st, 0);
return st;
}
function maximumOccurrence(arr, n, qs, qe) {
let freq_arr = new Array(n + 1);
let cnt = new Map();
for (let i = 0; i < n; i++)
cnt.set(arr[i], (cnt.get(arr[i]) || 0) + 1);
for (let i = 0; i < n; i++)
freq_arr[i] = cnt.get(arr[i]);
let st = constructST(freq_arr, n);
let maxOcc;
if (arr[qs] == arr[qe])
maxOcc = (qe - qs + 1);
else {
let leftmost_same = 0,
righmost_same = 0;
while (qs > 0 && qs <= qe && arr[qs] == arr[qs - 1]) {
qs++;
leftmost_same++;
}
while (qe >= qs && qe < n - 1 && arr[qe] == arr[qe + 1]) {
qe--;
righmost_same++;
}
maxOcc = Math.max(Math.max(leftmost_same, righmost_same), RMQ(st, n, qs, qe));
}
return maxOcc;
}
let arr = [-5, -5, 2, 2, 2, 2, 3, 7, 7, 7];
let n = arr.length;
let qs = 0;
let qe = 9;
console.log( "Maximum Occurrence in range is = " + maximumOccurrence(arr, n, qs, qe));
qs = 4;
qe = 9;
console.log( "Maximum Occurrence in range is = " + maximumOccurrence(arr, n, qs, qe));
|
OutputMaximum Occurrence in range is = 4
Maximum Occurrence in range is = 3
Further Optimization: For the partial overlapping case we have to run a loop to calculate the count of same numbers on both sides. To avoid this loop and perform this operation in O(1), we can store the index of the first occurrence of every number in the given array and hence by doing some precomputation we can find the required count in O(1).
Time Complexity: Time Complexity for tree construction is O(n). Time complexity to query is O(Log n).
Auxiliary Space: O(n)
Related Topic: Segment Tree