Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Array majority element - Am I missing something fundamental here?

Challenges • Asked over 3 years ago by

Commented on Oct 12, 2020:

While testing the solution for the majority element problem, it doesn't seem like given solution works I may be thinking about this incorrectly hence the post:

js
function majorityElement(nums) {
  var temp = nums.sort();
  return temp[Math.floor(nums.length/2)];
}

console.log(majorityElement([1,1,3,3,2,4,2,4]));

in the above sample, the given test case will return 3, which is not a majority element? The algorithm goes to a spot in the array where the majority element would be, but depending on the count of elements that may not be the majority element. So for instance, take this array returns 2 as the majority: [1,1,1,3,3,2,4,2,4]. Am I just overthinking a corner case or wrong completely?