LeetCode: Majority Element

Thank you for visiting this post! Be sure to also take a look at my other work on LinkedIn, Github, and my website.

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

--

--

--

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

Recommended from Medium

Vuex — solving old problems with new methods

No-Brainer HTML, JS, CSS and cypress.io testing starter tutorial — Part 4

Rocket Chat: Skip Initial Setup Wizard

Getting started with NodeJs

Next JS

Create Todo List with React Hooks, Context API, React UI and Firebase

How to use a custom dialogue with the canDeactivate route guard in Angular

10 Best Web Development Software for Web Developers

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
Stephanie Segura

Stephanie Segura

More from Medium

Linked Lists — What are they?

MCLT — More Code Less Talk

The pandemic of Data Structures and Algorithms Courses

Competitive Programming Grader For All Programmers

Data Structure Problem| Sort Colors in-Place | Part 2