Majority of Elements

During my daily Leetcode challenge I ran into an interesting problem, the Majority of elements. I was required to take the most frequent number in the array. The question states, “Given an array nums of size n, return the majority element”. For example, given an array of integers that is repeated frequently, return the integer that appears the most.

Since it's the majority we can find it through the center which will reveal the majority. The Aha moment I found was if the numbers were sorted from small to greatest the majority integer will eventually land in the middle. Therefore I used the sorting technique in this problem.

I would then sum up the length of the array to determine where the majority of numbers were if divided evenly. If it was divided evenly I would return the length divided by 2 to access the majority number Here’s a closer look below.

Otherwise, If the length had a remainder and did not divide evenly I would subtract 1 from the length and divide by 2 to access the frequent number. Here is a closer look below.

Thanks for reading till next time coders.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store