Most Frequent Number in Intervals in C++


Suppose we have a list of lists of integers intervals where each element has interval like [start, end]. We have to find the most frequently occurred number in the intervals. If there are ties, then return the smallest number.

So, if the input is like [[2, 5],[4, 6],[7, 10],[8, 10]], then the output will be 4

To solve this, we will follow these steps −

  • Define one map m

  • cnt := 0, val := 0

  • for each value it in x −

    • (increase m[it[0]] by 1)

    • decrease m[it[1] + 1] by 1

  • last := 0

  • for each key it in m

    • last := last + value of it

    • if last > cnt, then:

      • cnt := last

      • val := it

  • return val

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int solve(vector<vector<int>>& x) {
      map <int, int> m;
      int cnt = 0;
      int val = 0;
      for(auto& it : x){
         m[it[0]]++;
         m[it[1] + 1]--;
      }
      int last = 0;
      for(auto& it : m){
         last += it.second;
         if(last > cnt){
            cnt = last;
            val = it.first;
         }
      }
      return val;
   }
};
main() {
   Solution ob;
   vector<vector<int>> v = {{2, 5},{4, 6},{7, 10},{8, 10}};
   cout << ob.solve(v);
}

Input −

{{2, 5},{4, 6},{7, 10},{8, 10}}

Output

4

Updated on: 02-Sep-2020

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements