Skip to content

Instantly share code, notes, and snippets.

@bharathmuppa
Last active June 25, 2020 08:02
Show Gist options
  • Select an option

  • Save bharathmuppa/d2cdf2465e228dfa2de515d639a493ec to your computer and use it in GitHub Desktop.

Select an option

Save bharathmuppa/d2cdf2465e228dfa2de515d639a493ec to your computer and use it in GitHub Desktop.
/*
Given an array of size n, find the majority element.
The majority element is the element that appears more than floor(n/2) times.
You may assume that the array is non-empty and the majority element always exist in the array.
*/
/*
This solution complexity is
worst case : o(n)
best case: o(n/2) => though it is said as o(n), there is nothing wrong to mention as n/2 in best case
*/
function solution(A) {
let length = A.length;
switch (true) {
case (length <= 1):
return 0;
case (length > 1):
return getMajority(A);
default:
throw "I am weird case";
break;
}
}
function getMajority(A) {
const obj = {};
const highest = Math.floor(A.length / 2);
let firstHighest = 0;
let result = 0;
for (let i = 0; i < A.length; i++) {
let e = A[i];
if (!obj[e])
obj[e] = 1;
else {
obj[e] += 1;
obj[e] > firstHighest ? (result = e, firstHighest = obj[e]) : firstHighest;
if (firstHighest > Math.floor(A.length / 2)) {
// console.log("I will break here beacuse, no need to procees");
return result;
}
}
}
return result;
}
//solution([2,2,2,2,3,2,2,4,30,30,30,30,30,40]) => 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment