Maximum Occurrence in a Given Range
Last Updated :
11 Jul, 2025
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++
// C++ Program to find the occurrence
// of the most frequent number within
// a given range
#include <bits/stdc++.h>
using namespace std;
// A utility function to get the middle index
// from corner indexes.
int getMid(int s, int e) { return s + (e - s) / 2; }
/* A recursive function to get the maximum value in
a given range of array indexes. The following
are parameters for this function.
st --> Pointer to segment tree
index --> Index of current node in the segment
tree. Initially 0 is passed as root is
always at index 0
ss & se --> Starting and ending indexes of the
segment represented by current node,
i.e., st[index]
qs & qe --> Starting and ending indexes of query
range */
int RMQUtil(int* st, int ss, int se, int qs, int qe,
int index)
{
// If segment of this node is a part of given range,
// then return the min of the segment
if (qs <= ss && qe >= se)
return st[index];
// If segment of this node is outside the
// given range
if (se < qs || ss > qe)
return 0;
// If a part of this segment overlaps
// with the given range
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));
}
// Return minimum of elements in range from
// index qs (query start) to
// qe (query end). It mainly uses RMQUtil()
int RMQ(int* st, int n, int qs, int qe)
{
// Check for erroneous input values
if (qs < 0 || qe > n - 1 || qs > qe) {
printf("Invalid Input");
return -1;
}
return RMQUtil(st, 0, n - 1, qs, qe, 0);
}
// A recursive function that constructs Segment Tree
// for array[ss..se]. si is index of current node in
// segment tree st
int constructSTUtil(int arr[], int ss, int se, int* st,
int si)
{
// If there is one element in array, store it in
// current node of segment tree and return
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then
// recur for left and right subtrees and store
// the minimum of two values in this node
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];
}
/* Function to construct segment tree from given
array. This function allocates memory for segment
tree and calls constructSTUtil() to fill the
allocated memory */
int* constructST(int arr[], int n)
{
// Allocate memory for segment tree
// Height of segment tree
int x = (int)(ceil(log2(n)));
// Maximum size of segment tree
int max_size = 2 * (int)pow(2, x) - 1;
int* st = new int[max_size];
// Fill the allocated memory st
constructSTUtil(arr, 0, n - 1, st, 0);
// Return the constructed segment tree
return st;
}
int maximumOccurrence(int arr[], int n, int qs, int qe)
{
// Declaring a frequency array
int freq_arr[n + 1];
// Counting frequencies of all array elements.
unordered_map<int, int> cnt;
for (int i = 0; i < n; i++)
cnt[arr[i]]++;
// Creating frequency array by replacing the
// number in array to the number of times it
// has appeared in the array
for (int i = 0; i < n; i++)
freq_arr[i] = cnt[arr[i]];
// Build segment tree from this frequency array
int* st = constructST(freq_arr, n);
int maxOcc; // to store the answer
// Case 1: numbers are same at the starting
// and ending index of the query
if (arr[qs] == arr[qe])
maxOcc = (qe - qs + 1);
// Case 2: numbers are different
else {
int leftmost_same = 0, righmost_same = 0;
// Partial Overlap Case of a number with some
// occurrences lying inside the leftmost
// part of the range and some just before the
// range starts
while (qs > 0 && qs <= qe && arr[qs] == arr[qs - 1]) {
qs++;
leftmost_same++;
}
// Partial Overlap Case of a number with some
// occurrences lying inside the rightmost part of
// the range and some just after the range ends
while (qe >= qs && qe < n - 1 && arr[qe] == arr[qe + 1]) {
qe--;
righmost_same++;
}
// Taking maximum of all three
maxOcc = max({leftmost_same, righmost_same,
RMQ(st, n, qs, qe)});
}
return maxOcc;
}
// Driver Code
int main()
{
int arr[] = { -5, -5, 2, 2, 2, 2, 3, 7, 7, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
int qs = 0; // Starting index of query range
int qe = 9; // Ending index of query range
// Print occurrence of most frequent number
// within given range
cout << "Maximum Occurrence in range is = "
<< maximumOccurrence(arr, n, qs, qe) << endl;
qs = 4; // Starting index of query range
qe = 9; // Ending index of query range
// Print occurrence of most frequent number
// within given range
cout << "Maximum Occurrence in range is = "
<< maximumOccurrence(arr, n, qs, qe) << endl;
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.HashMap;
class GFG {
// A utility function to get the middle index
// from corner indexes.
public static int getMid(int s, int e) {
return s + (e - s) / 2;
}
/* A recursive function to get the maximum value in
a given range of array indexes. The following
are parameters for this function.
st --> Pointer to segment tree
index --> Index of current node in the segment
tree. Initially 0 is passed as root is
always at index 0
ss & se --> Starting and ending indexes of the
segment represented by current node,
i.e., st[index]
qs & qe --> Starting and ending indexes of query
range */
public static int RMQUtil(int[] st, int ss, int se, int qs, int qe,
int index) {
// If segment of this node is a part of given range,
// then return the min of the segment
if (qs <= ss && qe >= se)
return st[index];
// If segment of this node is outside the
// given range
if (se < qs || ss > qe)
return 0;
// If a part of this segment overlaps
// with the given range
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));
}
// Return minimum of elements in range from
// index qs (query start) to
// qe (query end). It mainly uses RMQUtil()
public static int RMQ(int[] st, int n, int qs, int qe) {
// Check for erroneous input values
if (qs < 0 || qe > n - 1 || qs > qe) {
System.out.println("Invalid Input");
return -1;
}
return RMQUtil(st, 0, n - 1, qs, qe, 0);
}
// A recursive function that constructs Segment Tree
// for array[ss..se]. si is index of current node in
// segment tree st
public static int constructSTUtil(int arr[], int ss, int se, int[] st,
int si) {
// If there is one element in array, store it in
// current node of segment tree and return
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then
// recur for left and right subtrees and store
// the minimum of two values in this node
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];
}
/* Function to construct segment tree from given
array. This function allocates memory for segment
tree and calls constructSTUtil() to fill the
allocated memory */
public static int[] constructST(int arr[], int n)
{
// Allocate memory for segment tree
// Height of segment tree
int x = (int)(Math.ceil(Math.log(n) / Math.log(2)));
// Maximum size of segment tree
int max_size = 2 * (int)Math.pow(2, x) - 1;
int[] st = new int[max_size];
// Fill the allocated memory st
constructSTUtil(arr, 0, n - 1, st, 0);
// Return the constructed segment tree
return st;
}
public static int maximumOccurrence(int arr[], int n, int qs, int qe)
{
// Declaring a frequency array
int freq_arr[] = new int[n + 1];
// Counting frequencies of all array elements.
HashMap<Integer, Integer> cnt = new HashMap<>();
for (int i = 0; i < n; i++)
cnt.put(arr[i], cnt.getOrDefault(arr[i], 0) + 1);
// Creating frequency array by replacing the
// number in array to the number of times it
// has appeared in the array
for (int i = 0; i < n; i++)
freq_arr[i] = cnt.get(arr[i]);
// Build segment tree from this frequency array
int[] st = constructST(freq_arr, n);
int maxOcc; // to store the answer
// Case 1: numbers are same at the starting
// and ending index of the query
if (arr[qs] == arr[qe])
maxOcc = (qe - qs + 1);
// Case 2: numbers are different
else {
int leftmost_same = 0, righmost_same = 0;
// Partial Overlap Case of a number with some
// occurrences lying inside the leftmost
// part of the range and some just before the
// range starts
while (qs > 0 && qs <= qe && arr[qs] == arr[qs - 1]) {
qs++;
leftmost_same++;
}
// Partial Overlap Case of a number with some
// occurrences lying inside the rightmost part of
// the range and some just after the range ends
while (qe >= qs && qe < n - 1 && arr[qe] == arr[qe + 1]) {
qe--;
righmost_same++;
}
// Taking maximum of all three
maxOcc = Math.max(Math.max(leftmost_same, righmost_same),
RMQ(st, n, qs, qe));
}
return maxOcc;
}
//driver code
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; // Starting index of query range
int qe = 9; // Ending index of query range
// Print occurrence of most frequent number
// within given range
System.out.println("Maximum Occurrence in range is = " + maximumOccurrence(arr, n, qs, qe));
qs = 4; // Starting index of query range
qe = 9; // Ending index of query range
// Print occurrence of most frequent number
// within given range
System.out.println("Maximum Occurrence in range is = " + maximumOccurrence(arr, n, qs, qe));
}
}
Python3
# Python 3 Program to find the occurrence
# of the most frequent number within
# a given range
from collections import defaultdict
import math
# A utility function to get the middle index
# from corner indexes.
def getMid(s, e):
return s + (e - s) // 2
''' A recursive function to get the maximum value in
a given range of array indexes. The following
are parameters for this function.
st --> Pointer to segment tree
index --> Index of current node in the segment
tree. Initially 0 is passed as root is
always at index 0
ss & se --> Starting and ending indexes of the
segment represented by current node,
i.e., st[index]
qs & qe --> Starting and ending indexes of query
range '''
def RMQUtil(st, ss, se, qs, qe, index):
# If segment of this node is a part of given range
# then return the min of the segment
if (qs <= ss and qe >= se):
return st[index]
# If segment of this node is outside the
# given range
if (se < qs or ss > qe):
return 0
# If a part of this segment overlaps
# with the given range
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))
# Return minimum of elements in range from
# index qs (query start) to
# qe (query end). It mainly uses RMQUtil()
def RMQ(st, n, qs, qe):
# Check for erroneous input values
if (qs < 0 or qe > n - 1 or qs > qe):
prf("Invalid Input")
return -1
return RMQUtil(st, 0, n - 1, qs, qe, 0)
# A recursive function that constructs Segment Tree
# for array[ss..se]. si is index of current node in
# segment tree st
def constructSTUtil(arr, ss, se, st,
si):
# If there is one element in array, store it in
# current node of segment tree and return
if (ss == se):
st[si] = arr[ss]
return arr[ss]
# If there are more than one elements, then
# recur for left and right subtrees and store
# the minimum of two values in this node
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]
''' Function to construct segment tree from given
array. This function allocates memory for segment
tree and calls constructSTUtil() to fill the
allocated memory '''
def constructST(arr, n):
# Allocate memory for segment tree
# Height of segment tree
x = (math.ceil(math.log2(n)))
# Maximum size of segment tree
max_size = 2 * pow(2, x) - 1
st = [0]*max_size
# Fill the allocated memory st
constructSTUtil(arr, 0, n - 1, st, 0)
# Return the constructed segment tree
return st
def maximumOccurrence(arr, n, qs, qe):
# Declaring a frequency array
freq_arr = [0]*(n + 1)
# Counting frequencies of all array elements.
cnt = defaultdict(int)
for i in range(n):
cnt[arr[i]] += 1
# Creating frequency array by replacing the
# number in array to the number of times it
# has appeared in the array
for i in range(n):
freq_arr[i] = cnt[arr[i]]
# Build segment tree from this frequency array
st = constructST(freq_arr, n)
maxOcc = 0 # to store the answer
# Case 1: numbers are same at the starting
# and ending index of the query
if (arr[qs] == arr[qe]):
maxOcc = (qe - qs + 1)
# Case 2: numbers are different
else:
leftmost_same = 0
righmost_same = 0
# Partial Overlap Case of a number with some
# occurrences lying inside the leftmost
# part of the range and some just before the
# range starts
while (qs > 0 and qs <= qe and arr[qs] == arr[qs - 1]):
qs += 1
leftmost_same += 1
# Partial Overlap Case of a number with some
# occurrences lying inside the rightmost part of
# the range and some just after the range ends
while (qe >= qs and qe < n - 1 and arr[qe] == arr[qe + 1]):
qe -= 1
righmost_same += 1
# Taking maximum of all three
maxOcc = max([leftmost_same, righmost_same,
RMQ(st, n, qs, qe)])
return maxOcc
# Driver Code
if __name__ == "__main__":
arr = [-5, -5, 2, 2, 2, 2, 3, 7, 7, 7]
n = len(arr)
qs = 0 # Starting index of query range
qe = 9 # Ending index of query range
# Print occurrence of most frequent number
# within given range
print("Maximum Occurrence in range is = ",
maximumOccurrence(arr, n, qs, qe))
qs = 4 # Starting index of query range
qe = 9 # Ending index of query range
# Print occurrence of most frequent number
# within given range
print("Maximum Occurrence in range is = ",
maximumOccurrence(arr, n, qs, qe))
# This code is contributed by ukasp.
C#
// C# code addition
using System;
using System.Collections.Generic;
class GFG
{
// A utility function to get the middle index
// from corner indexes.
public static int GetMid(int s, int e)
{
return s + (e - s) / 2;
}
/* A recursive function to get the maximum value in
a given range of array indexes. The following
are parameters for this function.
st --> Pointer to segment tree
index --> Index of current node in the segment
tree. Initially 0 is passed as root is
always at index 0
ss & se --> Starting and ending indexes of the
segment represented by current node,
i.e., st[index]
qs & qe --> Starting and ending indexes of query
range */
public static int RMQUtil(int[] st, int ss, int se, int qs, int qe,
int index)
{
// If segment of this node is a part of given range,
// then return the min of the segment
if (qs <= ss && qe >= se)
return st[index];
// If segment of this node is outside the
// given range
if (se < qs || ss > qe)
return 0;
// If a part of this segment overlaps
// with the given range
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));
}
// Return minimum of elements in range from
// index qs (query start) to
// qe (query end). It mainly uses RMQUtil()
public static int RMQ(int[] st, int n, int qs, int qe)
{
// Check for erroneous input values
if (qs < 0 || qe > n - 1 || qs > qe)
{
Console.WriteLine("Invalid Input");
return -1;
}
return RMQUtil(st, 0, n - 1, qs, qe, 0);
}
// A recursive function that constructs Segment Tree
// for array[ss..se]. si is index of current node in
// segment tree st
public static int ConstructSTUtil(int[] arr, int ss, int se, int[] st,
int si)
{
// If there is one element in array, store it in
// current node of segment tree and return
if (ss == se)
{
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then
// recur for left and right subtrees and store
// the minimum of two values in this node
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];
}
/* Function to construct segment tree from given
array. This function allocates memory for segment
tree and calls constructSTUtil() to fill the
allocated memory */
public static int[] ConstructST(int[] arr, int n)
{
// Allocate memory for segment tree
// Height of segment tree
int x = (int)Math.Ceiling(Math.Log(n, 2));
// Maximum size of segment tree
int max_size = 2 * (int)Math.Pow(2, x) - 1;
int[] st = new int[max_size];
// Fill the allocated memory st
ConstructSTUtil(arr, 0, n - 1, st, 0);
// Return the constructed segment tree
return st;
}
public static int maximumOccurrence(int[] arr, int n, int qs, int qe)
{
// Declaring a frequency array
int[] freq_arr = new int[n + 1];
// Counting frequencies of all array elements.
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]]++;
}
// Creating frequency array by replacing the
// number in array to the number of times it
// has appeared in the array
for (int i = 0; i < n; i++)
freq_arr[i] = cnt[arr[i]];
// Build segment tree from this frequency array
int[] st = ConstructST(freq_arr, n);
int maxOcc; // to store the answer
// Case 1: numbers are same at the starting
// and ending index of the query
if (arr[qs] == arr[qe])
maxOcc = (qe - qs + 1);
// Case 2: numbers are different
else {
int leftmost_same = 0, righmost_same = 0;
// Partial Overlap Case of a number with some
// occurrences lying inside the leftmost
// part of the range and some just before the
// range starts
while (qs > 0 && qs <= qe && arr[qs] == arr[qs - 1]) {
qs++;
leftmost_same++;
}
// Partial Overlap Case of a number with some
// occurrences lying inside the rightmost part of
// the range and some just after the range ends
while (qe >= qs && qe < n - 1 && arr[qe] == arr[qe + 1]) {
qe--;
righmost_same++;
}
// Taking maximum of all three
maxOcc = Math.Max(Math.Max(leftmost_same, righmost_same),
RMQ(st, n, qs, qe));
}
return maxOcc;
}
//driver code
static void Main() {
int[] arr = { -5, -5, 2, 2, 2, 2, 3, 7, 7, 7 };
int n = arr.Length;
int qs = 0; // Starting index of query range
int qe = 9; // Ending index of query range
// Print occurrence of most frequent number
// within given range
Console.WriteLine("Maximum Occurrence in range is = " + maximumOccurrence(arr, n, qs, qe));
qs = 4; // Starting index of query range
qe = 9; // Ending index of query range
// Print occurrence of most frequent number
// within given range
Console.WriteLine("Maximum Occurrence in range is = " + maximumOccurrence(arr, n, qs, qe));
}
}
// the code is contributed by Nidhi goel.
JavaScript
function getMid(s, e) {
/* A recursive function to get the maximum value in
a given range of array indexes. The following
are parameters for this function.
st --> Pointer to segment tree
index --> Index of current node in the segment
tree. Initially 0 is passed as root is
always at index 0
ss & se --> Starting and ending indexes of the
segment represented by current node,
i.e., st[index]
qs & qe --> Starting and ending indexes of query
range */
return s + Math.floor((e - s) / 2);
}
function RMQUtil(st, ss, se, qs, qe, index) {
// If segment of this node is a part of given range,
// then return the min of the segment
if (qs <= ss && qe >= se)
return st[index];
// If segment of this node is outside the
// given range
if (se < qs || ss > qe)
return 0;
// If a part of this segment overlaps
// with the given range
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));
}
// Return minimum of elements in range from
// index qs (query start) to
// qe (query end). It mainly uses RMQUtil()
function RMQ(st, n, qs, qe) {
// Check for erroneous input values
if (qs < 0 || qe > n - 1 || qs > qe) {
console.log("Invalid Input");
return -1;
}
return RMQUtil(st, 0, n - 1, qs, qe, 0);
}
// A recursive function that constructs Segment Tree
// for array[ss..se]. si is index of current node in
// segment tree st
function constructSTUtil(arr, ss, se, st, si) {
// If there is one element in array, store it in
// current node of segment tree and return
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then
// recur for left and right subtrees and store
// the minimum of two values in this node
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 to construct segment tree from given
array. This function allocates memory for segment
tree and calls constructSTUtil() to fill the
allocated memory */
function constructST(arr, n) {
// Allocate memory for segment tree
// Height of segment tree
let x = Math.ceil(Math.log2(n));
// Maximum size of segment tree
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) {
// Declaring a frequency array
let freq_arr = new Array(n + 1);
// Counting frequencies of all array elements.
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;
// to store the answer
if (arr[qs] == arr[qe])
maxOcc = (qe - qs + 1);
else {
let leftmost_same = 0,
righmost_same = 0;
// Partial Overlap Case of a number with some
// occurrences lying inside the leftmost
// part of the range and some just before the
// range starts
while (qs > 0 && qs <= qe && arr[qs] == arr[qs - 1]) {
qs++;
leftmost_same++;
}
// Partial Overlap Case of a number with some
// occurrences lying inside the rightmost part of
// the range and some just after the range ends
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; // Starting index of query range
let qe = 9; // Ending index of query range
console.log("Maximum Occurrence in range is = " + maximumOccurrence(arr, n, qs, qe));
qs = 4; // Starting index of query range
qe = 9; // Ending index of query range
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
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem