Our highlighted Algorithm for the week asks us to find the majority element in array that appears more than [n/2] times.
I have to admit, I had a hard time with this one. Luckily, I had the awesome support from my study group to help along the way.
I definitely learned a lot from it. Let’s get started!
Problem
Please click the link below to view the Problem Statement
Solution
For my own sanity, let’s breakdown what’s happening above. We declared a variable to hold the needed formula to find the majority element and an empty object in the newObj variable.
The
Math.floor()
function returns the largest integer less than or equal to a given number. — MDN Docs
We created a for loop iterating through the nums array and declare the variable value to hold the index of nums. We’re then assigning a value to the newObj’s key and checking to see if the element exists. If it does, add 1 to the value, if not, make the value 1.
And finally, we make a conditional statement checking our newObj against the formula we declared on line 4.
As always, here is a faster, optimal, one liner solution! This is not my code! I’ve linked the programmer’s LeetCode solution below. Please check him out!
Conclusion
Thank you so much for stopping by! Stay tuned for more Algorithm Content!
Please checkout my online portfolio and feel free to connect with me on Linkedin!
Sources:
https://leetcode.com/problems/majority-element/discuss/1146085/javascript-one-liner ,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor