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.

function majorityElement(num){}console.log(majorityElement([2,2,1,1,1,2,2]))

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.

function majorityElement(num){num.sort((a,b) => a - b)}

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.

function majorityElement(num){num.sort((a,b) => a - b)let total = num.lengthif(total % 2 === 0){
return num[total / 2]
}
}

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.

function majorityElement(num){num.sort((a,b) => a - b)let total = num.lengthif(total % 2 === 0){
return num[total / 2]
} else {
return num[(total - 1) / 2]
}
}console.log(majorityElement([2,2,1,1,1,2,2]))

Thanks for reading till next time coders.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Using Brotli with Preact — CLI 3

How to test your React-Redux Application

Creating Firefox browser extensions-14

10 interview questions every JavaScript developer should know

How to build a multilingual website in Next.js

Custom Sort String Challenge (Javascript)

JavaScript

The Power of the Composite Design Pattern in JavaScript

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
Woodelin florveus

Woodelin florveus

More from Medium

Scary Hoisting!!!

The Two Sum Problem: Using a Hash Table (sort of)

Make it right with good practices

Linked List Data Structure and Memory Allocation