# Maximum occurred integer in n ranges

• Difficulty Level : Hard
• Last Updated : 27 Oct, 2021

Given n ranges of the form L and R, the task is to find the maximum occurred integer in all the ranges. If more than one such integer exists, print the smallest one.
0 <= Li, Ri < 1000000.
Examples :

```Input : L1 = 1 R1 = 15
L2 = 4 R2 = 8
L3 = 3 R3 = 5
L3 = 1 R3 = 4
Output : 4

Input : L1 = 1 R1 = 15
L2 = 5 R2 = 8
L3 = 9 R3 = 12
L4 = 13 R4 = 20
L5 = 21 R5 = 30
Output : 5
Numbers having maximum occurrence i.e 2  are 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15. The smallest number
among all are 5.```

Become a success story instead of just reading about them. Prepare for coding interviews at Amazon and other top product-based companies with our Amazon Test Series. Includes topic-wise practice questions on all important DSA topics along with 10 practice contests of 2 hours each. Designed by industry experts that will surely help you practice and sharpen your programming skills. Wait no more, start your preparation today!

### Naive Approach:-  Time Complexity O(N*M)

We traverse through all the ranges. Then for every range, we count frequencies, we make a hash table or hash map where we store every item. Then you travel through other ranges and increment the frequency of every item. The item with the highest frequency is our answer. But this solution requires time say there are N ranges and if M is the maximum number of elements in any of the ranges, then it’s going to take O(N*M) time. The hash table has the time complexity of insert and search and delete as O(1). So you can insert every item in the hash table and its frequency in O(1).

### Efficient Approach:-  Time Complexity O(N + max)

We can do this in better time complexity if the ranges are fixed say (0 <= Li, Ri < 1000000). The trick here is we don’t want to travel every element of every range. We only want to travel through all ranges and we want to use the prefix sum technique to solve this problem.

We create a vector/Arraylist/Array. All the values in the vector are initialized by zero (use the vector or ArrayList to avoid that extra line of .memset() in c++ or .fill() in java). So what we do is we loop through every range and mark the presence of the beginning of every range. We simply do this arr[L[i]]++. We also mark the end of this range by subtracting one from arr[R[i+1]].

As I discussed earlier, we Mark the presence of the beginning of every range as one.

So if I do a prefix sum and if I Mark the beginning, all the values will be incremented by one after this element. Now we want to increment only till the end of the array. We do not want to increment other elements.

Let say,

L[] = {1, 2, 3} , R[] = {3, 5 , 7}

1. for this line arr[L[i]]++ the array becomes {0,1,1,1,0,0,0,0,……}

2. for this line arr[R[i+1]]– the array becomes  {0,1,1,1,-1, 0, -1, 0,-1,……}

3. when we do prefix sum the array becomes {0,1,2,3,2,2,1,1,0…}

When we do prefix sum, we’ll have the sum of elements after (1) incremented by one because I marked the beginning. Now I do not want this increment to happen to elements after (3). So if there’s a range one, two, three, the values from one, two, three should only be incremented by one or their frequency should be incremented by one.

That is why we decrease the value of arr[R[i+1]]. So that elements after the end of this range have values minus one subtracted. That is how we nullify the impact of incrementing the value when I’m going to do the prefix.

So when I’m going to do the prefix, I’m simply going to increment every value after the range, since I want to increment only in the range. That’s the idea of this algorithm.

## C++

 `// C++ program to find maximum occurred element in``// given N ranges.``#include ``#define MAX 1000000``using` `namespace` `std;` `// Return the maximum occurred element in all ranges.``int` `maximumOccurredElement(``int` `L[], ``int` `R[], ``int` `n)``{``    ``// Initialising all element of array to 0.``    ``int` `arr[MAX];``    ``memset``(arr, 0, ``sizeof` `arr);` `    ``// Adding +1 at Li index and substracting 1``    ``// at Ri index.``    ``int` `maxi=-1;``    ``for` `(``int` `i = 0; i < n; i++) {``        ``arr[L[i]] += 1;``        ``arr[R[i] + 1] -= 1;``        ``if``(R[i]>maxi){``            ``maxi=R[i];``        ``}``    ``}` `    ``// Finding prefix sum and index having maximum``    ``// prefix sum.``    ``int` `msum = arr,ind;``    ``for` `(``int` `i = 1; i < maxi+1; i++) {``        ``arr[i] += arr[i - 1];``        ``if` `(msum < arr[i]) {``            ``msum = arr[i];``            ``ind = i;``        ``}``    ``}` `    ``return` `ind;``}` `// Driven Program``int` `main()``{``    ``int` `L[] = { 1, 4, 9, 13, 21 };``    ``int` `R[] = { 15, 8, 12, 20, 30 };``    ``int` `n = ``sizeof``(L) / ``sizeof``(L);` `    ``cout << maximumOccurredElement(L, R, n) << endl;``    ``return` `0;``}`

## Java

 `// Java program to find maximum occurred``// element in given N ranges.``import` `java.io.*;` `class` `GFG {` `    ``static` `int` `MAX = ``1000000``;` `    ``// Return the maximum occurred element in all ranges.``    ``static` `int` `maximumOccurredElement(``int``[] L, ``int``[] R, ``int` `n)``    ``{``        ``// Initialising all element of array to 0.``        ``int``[] arr = ``new` `int``[MAX];` `        ``// Adding +1 at Li index and``        ``// substracting 1 at Ri index.``        ``int` `maxi=-``1``;``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``arr[L[i]] += ``1``;``            ``arr[R[i] + ``1``] -= ``1``;``            ``if``(R[i]>maxi){``            ``maxi=R[i];``           ``}``        ``}` `        ``// Finding prefix sum and index``        ``// having maximum prefix sum.``        ``int` `msum = arr[``0``];``        ``int` `ind = ``0``;``        ``for` `(``int` `i = ``1``; i < maxi+``1``; i++) {``            ``arr[i] += arr[i - ``1``];``            ``if` `(msum < arr[i]) {``                ``msum = arr[i];``                ``ind = i;``            ``}``        ``}` `        ``return` `ind;``    ``}` `    ``// Driver program``    ``static` `public` `void` `main(String[] args)``    ``{``        ``int``[] L = { ``1``, ``4``, ``9``, ``13``, ``21` `};``        ``int``[] R = { ``15``, ``8``, ``12``, ``20``, ``30` `};``        ``int` `n = L.length;``        ``System.out.println(maximumOccurredElement(L, R, n));``    ``}``}` `// This code is contributed by vt_m.`

## Python3

 `# Python 3 program to find maximum occurred``# element in given N ranges.` `MAX` `=` `1000000` `# Return the maximum occurred element``# in all ranges.``def` `maximumOccurredElement(L, R, n):``    ` `    ``# Initialising all element of array to 0.``    ``arr ``=` `[``0` `for` `i ``in` `range``(``MAX``)]` `    ``# Adding +1 at Li index and substracting 1``    ``# at Ri index.``    ``for` `i ``in` `range``(``0``, n, ``1``):``        ``arr[L[i]] ``+``=` `1``        ``arr[R[i] ``+` `1``] ``-``=` `1` `    ``# Finding prefix sum and index``    ``# having maximum prefix sum.``    ``msum ``=` `arr[``0``]``    ``for` `i ``in` `range``(``1``, ``MAX``, ``1``):``        ``arr[i] ``+``=` `arr[i ``-` `1``]``        ``if` `(msum < arr[i]):``            ``msum ``=` `arr[i]``            ``ind ``=` `i``    ``return` `ind` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``L ``=` `[``1``, ``4``, ``9``, ``13``, ``21``]``    ``R ``=` `[``15``, ``8``, ``12``, ``20``, ``30``]``    ``n ``=` `len``(L)` `    ``print``(maximumOccurredElement(L, R, n))``    ` `# This code is contributed by``# Sanjit_Prasad`

## C#

 `// C# program to find maximum``// occurred element in given N ranges.``using` `System;` `class` `GFG {` `    ``static` `int` `MAX = 1000000;` `    ``// Return the maximum occurred element in all ranges.``    ``static` `int` `maximumOccurredElement(``int``[] L, ``int``[] R, ``int` `n)``    ``{``        ``// Initialising all element of array to 0.``        ``int``[] arr = ``new` `int``[MAX];` `        ``// Adding +1 at Li index and``        ``// substracting 1 at Ri index.``        ``for` `(``int` `i = 0; i < n; i++) {``            ``arr[L[i]] += 1;``            ``arr[R[i] + 1] -= 1;``        ``}` `        ``// Finding prefix sum and index``        ``// having maximum prefix sum.``        ``int` `msum = arr;``        ``int` `ind = 0;``        ``for` `(``int` `i = 1; i < MAX; i++) {``            ``arr[i] += arr[i - 1];``            ``if` `(msum < arr[i]) {``                ``msum = arr[i];``                ``ind = i;``            ``}``        ``}` `        ``return` `ind;``    ``}` `    ``// Driver program``    ``static` `public` `void` `Main()``    ``{``        ``int``[] L = { 1, 4, 9, 13, 21 };``        ``int``[] R = { 15, 8, 12, 20, 30 };``        ``int` `n = L.Length;``        ``Console.WriteLine(maximumOccurredElement(L, R, n));``    ``}``}` `// This code is contributed by vt_m.`

## PHP

 ``

## Javascript

 ``

Output:

`4`

Time Complexity: O(n + MAX)

Exercise: Try for 0 <= Li, Ri <= 1000000000. (Hint: Use stl map).
Related Article: Maximum value in an array after m range increment operations
This article is contributed by KaaL-EL. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.