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!
Please click the link below to view the Problem Statement
Majority Element - LeetCode
Given an array nums of size n, return the majority element. The majority element is the element that appears more than…
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.
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!
Thank you so much for stopping by! Stay tuned for more Algorithm Content!
Stephanie Segura - Lone Star College - Houston, Texas, United States | LinkedIn
Hi there! My name is Stephanie. I am a Full-Stack Software Engineer residing in Houston, TX. Building on my business…