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


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

Updated on: 29-Apr-2020

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements