Given an array arr[] of N integers. The task is to create a frequency array freq[] of the given array arr[] and find the maximum element of the frequency array. If two elements have the same frequency in the array freq[], then return the element which has a smaller value.
Examples:
Input: arr[] = {1, 1, 1, 2, 3, 2, 2, 3, 5, 5, 5, 5, 4, 4, 4, 4, 4};Â
Output: 3Â
Explanation:Â
frequency of elements is given by:Â
val -> freq[]Â
1 -> 3Â
2 -> 3Â
3 -> 2Â
4 -> 5Â
5 -> 4Â
Element 3 has the maximum frequency in the frequency array.Input: arr[] = { 3, 5, 15, 51, 15, 14, 14, 14, 14, 4};Â
Output: 1Â
Explanation:Â
frequency of elements is given by:Â
val -> freq[]Â
3 -> 1Â
4 -> 1Â
5 -> 1Â
14 -> 4Â
15 -> 2Â
51 -> 1Â
Element 1 has the maximum frequency in the frequency array.Â
Â
Approach:
- Store the frequency of the elements of arr[] in a map say map1, with elements of arr[] as key and their frequency as value.
- Now, store the frequency of elements of map1 in some other map say map2.
- Traverse map2 to get the highest element.
- If there is multiple highest element than the element which has lower value is print.
Below is the implementation of the above approach:
C++14
// C++14 program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to get the highest// frequency of frequency arrayint findElement(int a[], int n){    // To find the maximum frequency    // initialize it with INT_MIN    int mx = INT_MIN;    int ans = 0;Â
    // Initialize maps to store the    // count of element in array    map<int, int> map1, map2;Â
    // Store the frequency of    // element of array in map1    for (int i = 0; i < n; i++) {        map1[a[i]]++;    }Â
    // Storing the frequency i.e.,    // (x.second) which is count of    // element in array    for (auto x : map1) {        map2[x.second]++;    }Â
    for (auto x : map2) {Â
        // Check if the frequency of        // element is greater than mx        if (x.second > mx) {            mx = x.second;Â
            // Store the value to check            // when frequency is same            ans = x.first;        }Â
        // If frequency of 2 element is        // same than storing minimum value        else if (x.second == mx) {            ans = min(ans, x.first);        }    }Â
    // Return the highest frequency    return ans;}Â
// Driver Codeint main(){    // Given array arr[]    int arr[] = { 1, 1, 1, 2, 3, 2, 2, 3, 5,                  5, 5, 5, 4, 4, 4, 4, 4 };Â
    // Size of the array    int n = sizeof(arr) / sizeof(arr[0]);Â
    // Function Call    cout << findElement(arr, n) << endl;} |
Java
// Java program for the above approachimport java.util.*;Â
class GFG{Â
// Function to get the highest// frequency of frequency arraystatic int findElement(int a[], int n){         // To find the maximum frequency    // initialize it with INT_MIN    int mx = Integer.MIN_VALUE;    int ans = 0;Â
    // Initialize maps to store the    // count of element in array    Map<Integer, Integer> map1 = new HashMap<>(),                          map2 = new HashMap<>();Â
    // Store the frequency of    // element of array in map1    for(int i = 0; i < n; i++)    {        map1.put(a[i], map1.getOrDefault(a[i], 0) + 1);    }Â
    // Storing the frequency i.e.,    // (x.second) which is count of    // element in array    for(Integer x : map1.values())     {        map2.put(x, map2.getOrDefault(x, 0) + 1);    }Â
    for(Map.Entry<Integer, Integer> x : map2.entrySet())    {                 // Check if the frequency of        // element is greater than mx        if (x.getValue() > mx)        {            mx = x.getValue();Â
            // Store the value to check            // when frequency is same            ans = x.getKey();        }Â
        // If frequency of 2 element is        // same than storing minimum value        else if (x.getValue() == mx)        {            ans = Math.min(ans, x.getKey());        }    }Â
    // Return the highest frequency    return ans;}Â
// Driver codepublic static void main (String[] args) {         // Given array arr[]    int arr[] = { 1, 1, 1, 2, 3, 2, 2, 3, 5,                  5, 5, 5, 4, 4, 4, 4, 4 };         // Size of the array    int n = arr.length;         // Function call    System.out.println(findElement(arr, n));}}Â
// This code is contributed by offbeat |
Python3
# Python3 program for the above approachimport sysÂ
# Function to get the highest# frequency of frequency arraydef findElement(a, n):         # To find the maximum frequency    # initialize it with INT_MIN    mx = -sys.maxsize - 1    ans = 0Â
    # Initialize maps to store the    # count of element in array    map1 = {}    map2 = {}Â
    # Store the frequency of    # element of array in map1    for i in a:        map1[i] = map1.get(i, 0) + 1Â
    # Storing the frequency i.e.,    # (x.second) which is count of    # element in array    for x in map1:        map2[map1[x]] = map2.get(map1[x], 0) + 1Â
    for x in map2:Â
        # Check if the frequency of        # element is greater than mx        if (map2[x] > mx):            mx = map2[x]Â
            # Store the value to check            # when frequency is same            ans = xÂ
        # If frequency of 2 element is        # same than storing minimum value        elif (map2[x] == mx):            ans = min(ans, x)Â
    # Return the highest frequency    return ansÂ
# Driver Codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â # Given array arr[]Â Â Â Â arr = [ 1, 1, 1, 2, 3, 2, 2, 3, Â Â Â Â Â Â Â Â Â Â Â Â 5, 5, 5, 5, 4, 4, 4, 4, 4]Â
    # Size of the array    n = len(arr)Â
    # Function call    print(findElement(arr, n))Â
# This code is contributed by mohit kumar 29 |
C#
// C# program for the above approachusing System;using System.Collections.Generic;Â
class GFG{     // Function to get the highest// frequency of frequency arraystatic int findElement(int[] a, int n){         // To find the maximum frequency    // initialize it with INT_MIN    int mx = Int32.MinValue;    int ans = 0;Â
    // Initialize maps to store the    // count of element in array    Dictionary<int,               int> map1 = new Dictionary<int,                                           int>(),                    map2 = new Dictionary<int,                                           int>();Â
    // Store the frequency of    // element of array in map1    for(int i = 0; i < n; i++)    {         if (map1.ContainsKey(a[i]))            map1[a[i]] = map1[a[i]] + 1;        else            map1[a[i]] = 1;    }Â
    // Storing the frequency i.e.,    // (x.second) which is count of    // element in array    foreach(KeyValuePair<int, int> xx in map1)    {        int x = xx.Value;        if (map2.ContainsKey(x))            map2[x] = map2[x] + 1;        else            map2[x] = 1;    }         foreach(KeyValuePair<int, int> x in map2)    {                 // Check if the frequency of        // element is greater than mx        if (x.Value > mx)        {            mx = x.Value;                         // Store the value to check            // when frequency is same            ans = x.Key;        }                 // If frequency of 2 element is        // same than storing minimum value        else if (x.Value == mx)        {            ans = Math.Min(ans, x.Key);        }    }         // Return the highest frequency    return ans;}     // Driver codestatic public void Main (){         // Given array arr[]    int[] arr = { 1, 1, 1, 2, 3, 2, 2, 3, 5,                  5, 5, 5, 4, 4, 4, 4, 4 };         // Size of the array    int n = arr.Length;         // Function call    Console.WriteLine(findElement(arr, n));}}Â
// This code is contributed by offbeat |
Javascript
<script>// Javascript program for the above approachÂ
// Function to get the highest// frequency of frequency arrayfunction findElement(a, n){    // To find the maximum frequency    // initialize it with INT_MIN    var mx = -1000000000;    var ans = 0;Â
    // Initialize maps to store the    // count of element in array    var map1 = new Map(), map2= new Map();Â
    // Store the frequency of    // element of array in map1    for (var i = 0; i < n; i++) {        if(map1.has(a[i]))            map1.set(a[i], map1.get(a[i])+1)        else            map1.set(a[i], 1);    }Â
    // Storing the frequency i.e.,    // (x.second) which is count of    // element in array    map1.forEach((value, key) => {                 if(map2.has(value))            map2.set(value, map2.get(value)+1)        else            map2.set(value, 1);    });Â
    map2.forEach((value, key) => {                 // Check if the frequency of        // element is greater than mx        if (value > mx) {            mx = value;Â
            // Store the value to check            // when frequency is same            ans = key;        }Â
        // If frequency of 2 element is        // same than storing minimum value        else if (value == mx) {            ans = Math.min(ans, key);        }    });Â
    // Return the highest frequency    return ans;}Â
// Driver Code// Given array arr[]var arr = [1, 1, 1, 2, 3, 2, 2, 3, 5,              5, 5, 5, 4, 4, 4, 4, 4];// Size of the arrayvar n = arr.length;// Function Calldocument.write( findElement(arr, n));Â
Â
Â
</script> |
3
Â
Time Complexity: O(N)
Auxiliary Space: O(N)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
