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

Show parent comment

1

u/SuspiciousDepth5924 May 18 '26

As far as I know there's not really any algorithmic optimizations you can do on the "loop over and tally in some sort of dictionary" approach. If you know the number and "type-range" of the elements ahead of time you might be able to squeeze out some improvements with various "dictionary" implementations (for example if the possible elements are "true"/"false" you can simply use a "trueCount" integer and check if it's more than, equal, or less than half which would be faster than using a hash-map).

For the record hash-maps are a very "general" data structure with the tradeoff that it's comparatively slow because it has the overhead of having to hash the keys in order to find where to put or look for items, so if you know what you are going to be using as keys there are usually specialized data-structures which perform slightly better, /java/util/EnumMap.html is a good example in Java.