Maximum occurred integer in n ranges using C++

In this problem, we are given N ranges. Our task is to maximum occurred integer in n ranges.

For the starting and ending value of all ranges. We need to find the value which occurs the most.

Let’s take an example to understand the problem,


S1 = 1, E1 = 3
S2 = 2, E2 = 6
S3 = 3, E3 = 4



Solution Approach

A simple approach t o solve the problem is by using hashing, we will use a hash table to count all members and their count. We will traverse all ranges and store count in the hash table, then we will find the maximum count.

Another approach to solve the problem in linear time is using a range array. In this array, we will update the index of all start values of range by adding 1 and all end values of range by subtracting 1 from it. The will find prefix sum and find the maximum prefix sum value.


Program to illustrate the working of our solution

#include <bits/stdc++.h>
#define MAX 1000000
using namespace std;
int findMaxOccrEle(int L[], int R[], int n){
   int occurenceConut[MAX];
   memset(occurenceConut, 0, sizeof occurenceConut);
   int maxi = -1;
   for (int i = 0; i < n; i++) {
      occurenceConut[L[i]] += 1;
      occurenceConut[R[i] + 1];
   int prefSum = occurenceConut[0],maxEleIndex;
   for (int i = 1; i < maxi+1; i++) {
      occurenceConut[i] += occurenceConut[i - 1];
      if (prefSum < occurenceConut[i]) {
         prefSum = occurenceConut[i];
         maxEleIndex = i;
   return maxEleIndex;
int main(){
   int L[] = { 1, 2, 3 };
   int R[] = { 3, 6, 4 };
   int n = sizeof(L) / sizeof(L[0]);
   cout<<"The maximum occurred integer in the range is "<<findMaxOccrEle(L, R, n);
   return 0;


The maximum occurred integer in the range is 3

Updated on: 14-Feb-2022


Kickstart Your Career

Get certified by completing the course

Get Started