Element Appearing More Than 25% In Sorted Array in C++

C++Server Side ProgrammingProgramming

Suppose we have an array A. There are few elements. Some elements are common. We have to return an element that is appearing more than 25% spaces in the array. So if A = [1, 2, 4, 4, 4, 4, 5, 5, 6, 6, 7, 7], Here 4 has occurred four times. This is more than 25% of 12 (size of the array)

To solve this, we will follow these steps −

  • Read elements and store their respective frequencies
  • If the frequency is greater than 25% of the array size, then return the result.

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
      int findSpecialInteger(vector<int>& arr) {
         int n = arr.size();
         int req = n / 4;
         unordered_map <int, int> m;
         int ans = -1;
         for(int i = 0; i < n; i++){
            m[arr[i]]++;
            if(m[arr[i]] > req)ans = arr[i];
         }
         return ans;
      }
};
main(){
   Solution ob;
   vector<int> c = {1,2,4,4,4,4,5,5,6,6,7,7};
   cout << ob.findSpecialInteger(c);
}

Input

[1,2,4,4,4,4,5,5,6,6,7,7]

Output

4
raja
Published on 20-Jan-2020 06:53:59
Advertisements