Maximum occurred integer in n ranges

06 Jul, 2022
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
        L4 = 1 R4 = 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.
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). 
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. 
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum occurred element in// given N ranges.#include <bits/stdc++.h>#define MAX 1000000using 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 subtracting 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],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 Programint main(){    int L[] = { 1, 4, 9, 13, 21 };    int R[] = { 15, 8, 12, 20, 30 };    int n = sizeof(L) / sizeof(L[0]);     cout << maximumOccurredElement(L, R, n) << endl;    return 0;}
// 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        // subtracting 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.
# 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 subtracting 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 Codeif __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# 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        // subtracting 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[0];        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// PHP program to find maximum occurred// element in given N ranges.$MAX = 1000000; // Return the maximum occurred element// in all ranges.function maximumOccurredElement($L, $R, $n){     // Initialising all element    // of array to 0.    $arr = array();    for($i = 0; $i < $n; $i++)    {        $arr[] = "0";    }     // Adding +1 at Li index and subtracting 1    // at Ri index.    for ($i = 0; $i < $n; $i++)    {        $arr[$L[$i]] += 1;        $arr[$R[$i] + 1] -= 1;    }         // Finding prefix sum and index    // having maximum prefix sum.    $msum = $arr[0];         for ($i = 1; $i <$n; $i++)    {        $arr[$i] += $arr[$i - 1];        if ($msum < $arr[$i])        {            $msum = $arr[$i];            $ind = $i;        }    }    return $ind;} // Driver Code$L = array(1, 4, 9, 13, 21);$R = array(15, 8, 12, 20, 30);$n = count($L); echo maximumOccurredElement($L, $R, $n); // This code is contributed by// Srathore?>
<script>     // JavaScript program to find maximum    // occurred element in given N ranges.         let MAX = 1000000;       // Return the maximum occurred element in all ranges.    function maximumOccurredElement(L, R, n)    {        // Initialising all element of array to 0.        let arr = new Array(MAX);        arr.fill(0);           // Adding +1 at Li index and        // subtracting 1 at Ri index.        for (let i = 0; i < n; i++) {            arr[L[i]] += 1;            arr[R[i] + 1] -= 1;        }           // Finding prefix sum and index        // having maximum prefix sum.        let msum = arr[0];        let ind = 0;        for (let i = 1; i < MAX; i++) {            arr[i] += arr[i - 1];            if (msum < arr[i]) {                msum = arr[i];                ind = i;            }        }           return ind;    }         let L = [ 1, 4, 9, 13, 21 ];    let R = [ 15, 8, 12, 20, 30 ];    let n = L.length;    document.write(maximumOccurredElement(L, R, n));     </script>
4
Time Complexity: O(n + MAX) 
Maximum Occurred Integer in N Ranges | DSA | Programming Tutorials | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersMaximum Occurred Integer in N Ranges | DSA | Programming Tutorials | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 14:46•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=czJe_yO1ruI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
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. 
vt_m
Sanjit_Prasad
sapnasingh4991
shreyashagrawal
Lohith sai Andra
Akanksha_Rai
rameshtravel07
gabaa406
kaalel
jitendranitrr13
sweetyty
dungaajay123
hardikkoriintern
Amazon
prefix-sum
Arrays
Amazon
prefix-sum
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Introduction to Arrays
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Python | Using 2D arrays/lists the right way