Find element with highest frequency in given nested Array

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:
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:
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:



  1. Store the frequency of the elements of arr[] in a map say map1, with elements of arr[] as key and their frequency as value.
  2. Now, store the frequency of elements of map1 in some other map say map2.
  3. Traverse map2 to get the highest element.
  4. 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

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++14 program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to get the highest
// frequency of frequency array
int 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 fequency 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 Code
int 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to get the highest
// frequency of frequency array
static 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 fequency 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 code
public 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
import sys
 
# Function to get the highest
# frequency of frequency array
def 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 fequency 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 Code
if __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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to get the highest
// frequency of frequency array
static 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 fequency 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 code
static 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

chevron_right


Output: 

3








 

Time Complexity: O(N)
Auxiliary Space: O(N)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Learn to Code A beginner in field of coding

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : mohit kumar 29, offbeat

Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.