Solving Leetcode’s Majority Element Problem in JavaScript

Return the majority element of an array, which is the element that appears more than ⌊ n/2 ⌋ times.
  • In order to know which element shows up the most, we’re going to have to iterate through the entire array. There’s just no way around this.
  • We’re going to have to figure out a way count how many of each element there is and refer back to this count later in order to know which one is the most frequent flyer in our array.
function majorityElement(nums) {
let numsObj = {};
let maxFreq = 0;
}
numsObj = {
2: 1,
3: 2
}
for (num in numsObj) {
if (numsObj[num] > maxFreq) {
maxFreq = numsObj[num];
maxElement = parseInt(num);
}
}
function majorityElement(nums) {
let numsObj = {};
let maxFreq = 0;
let maxElement = null;
for (let num of nums) {
numsObj[num] = numsObj[num] + 1 || 1;
}
for (num in numsObj) {
if (numsObj[num] > maxFreq) {
maxFreq = numsObj[num];
maxElement = parseInt(num);
}
}
return maxElement;
}

--

--

--

Always learning.

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

Recommended from Medium

What Is The Most Accurate Web Content Classification API In 2022?

May LeetCoding Challenge - 16

Free AI Voice Generators For Your Avatar

Web Animation API-llusion of Life

GiNZA Version 4.0:

Secondary constructors for clean network request bodies in Kotlin

Convert Any Currency To GBP With A Forex API

Is there any Text-To-Speech API with OCR?

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
Saul Feliz

Saul Feliz

Always learning.

More from Medium

How to Sort an Array without Using JavaScript’s Sort Method

Revelations: How JavaScript Works Behind The Scenes — part 03

Is the experience card really that meaningful in computer programming?

Why “this” gets undefined inside a function