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.
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.
A simple solution is to use hash table to store counts of all numbers. We traverse every interval from Li to Ri and increment count of all numbers present in every interval. Finally we traverse the hash table to find the number with maximum count. Time complexity of this solution is O(n * MAX_INTERVAL) where MAX_INTERVAL is maximum number of elements in an interval.
An efficient solution requires linear time. We create an array arr of size 1000000 (limit given on maximum value of an interval). The idea is to add +1 to each Li index and -1 to corresponding Ri index in arr. After this, find the prefix sum of the array. Adding +1 at Li shows the starting point of ith Range and adding -1 shows the ending point of ith range. Finally we return the array index that has maximum prefix sum
Algorithm to solve the problem:
- Initialize an array arr to 0.
- For each range i, add +1 at Li index and -1 at Ri of the array.
- Find the prefix sum of the array and find the smallest index having maximum prefix sum.
Below is the implementation of this approach:
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 Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Maximum occurred integer in n ranges | Set-2
- Elements that occurred only once in the array
- Products of ranges in an array
- Count Primes in Ranges
- Search an element in given N ranges
- Queries on probability of even or odd number in given ranges
- Find the missing elements from 1 to M in given N ranges | Set-2
- Find a range that covers all the elements of given N ranges
- Find the kth element in the series generated by the given N ranges
- Sliding Window Maximum (Maximum of all subarrays of size k)
- Replace all ‘0’ with ‘5’ in an input Integer
- Find the missing integer in an array if mean is given
- Convert a String to Integer Array in C/C++
- First negative integer in every window of size k
- Find an integer X which is divisor of all except exactly one element in an array