r/learnprogramming • • May 18 '26

Frequency of an Element in Array

Hey Guyz, How to find highest occuring element in Array not the maxELement Highest frequency ? I know hashMap solution but there are some confusions and doubts there I really didn't getting that solution but is the optimal one, so pliz explain in a little simple way.

0 Upvotes

8 comments sorted by

View all comments

2

u/opentabs-dev May 18 '26

if hashmap is what's tripping you up, just think of it as a tally sheet. you walk through the array once, and for each number you bump its count by 1. while you're doing that, also keep two extra variables: bestNum and bestCount. whenever you bump a count and the new count is higher than bestCount, update both. when the loop ends you already have the answer — no second pass needed.

counts = {}
bestNum, bestCount = None, 0
for x in arr:
    counts[x] = counts.get(x, 0) + 1
    if counts[x] > bestCount:
        bestCount = counts[x]
        bestNum = x

the "optimal" part isnt the hashmap itself, its that you only touch each element once. O(n) time, O(k) space where k is the number of distinct values.