Member-only story

Majority Element

Jack
2 min readDec 28, 2020

--

A majority element is defined as an element within an array that occurs more than n/2 times, where n is the length of array nums.

Write a function that returns the majority element in a given array.

Brute Force

Let’s start simple — brute force. This can easily be done with a double for loop. Run through the array and for each element run through the array again. If the outter and inner element are the same, increase the count. Check if your running count is greater than the majority — if so, return that number.

This is a quick and easy solution, but it does hurt out runtime. Since we are looping through the array twice, that leaves us with a time complexity of O(n²) and space complexity of O(1).

Can you think of a solution that has a faster runtime?

Hash

A solution that would save on time would utilize a hash. You can iterate through the array, and for each element either add it to a hash or increase it’s value in the hash by one. If the count ever exceeds the majority count, return that…

--

--

Jack
Jack

Written by Jack

Magician, Mathematician, and Software Engineer

No responses yet