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

Loose vs Strict Equality in JavaScript

A Practical guide to ES6 modules

Find Max and Min Value from an Array in JavaScript

Get Max and Min Value from an Array in JavaScript

js211 — blogPost_205

How to build a simple speech recognition app

Introduction to React.js

Voice Automating Spotify w/ React and Codesphere

let: let’s dive deep!

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

Construct a binary tree from given multi-dimensional array

Leetcode 34: Find First and Last Position of Element in Sorted Array

DSA #4 Binary Tree and Binary Search Tree

What is a Singly Linked List?