Python Program to Find Highest Frequency Element in Array

In this tutorial, We will learn to write a Python program to find the highest frequency element in an Array.

For Example:

Suppose we have an array arr = [1, 2, 3, 4, 5, 6, 5, 4, 5, 6, 5, 4, 3, 2, 1, 5, 6]

The highest frequency element should print 5, as 5 is repeated the most.

Program: Using a dictionary

With the help of a dictionary, we can find the highest-frequency element in an array. We will iterate each element of the array and count the frequency of each element. We will store this counting in a dictionary. The key of the dictionary will be the element, and the value will be the frequency. Those will be the highest frequency element whose value will be maximum in the dictionary. Below is the program.

arr = [1, 2, 3, 4, 5, 6, 5, 4, 5, 1, 2, 3, 4, 5, 6, 5, 4, 5]
freq_dict = {}
for element in arr:
    if element in freq_dict:
        freq_dict[element] += 1
    else:
        freq_dict[element] = 1
highest_freq_element = max(freq_dict, key=freq_dict.get)
print("Highest frequency element:", highest_freq_element)

Output

Highest frequency element: 5

Conclusion:

In this post, we have learned to write a Python program to find the element that has repeated most in the array. We have used a dictionary of Python to achieve this. Hope this program is helpful to you.