1 minute read

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Example 1:

Input: nums = [3,2,3] Output: 3 Example 2:

Input: nums = [2,2,1,1,1,2,2] Output: 2

/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function (nums) {
  let majority = nums[0];
  let count = 1;

  for (let i = 1; i < nums.length; i++) {
    if (nums[i] === majority) {
      count++;
    } else {
      count--;
    }

    if (count === 0) {
      majority = nums[i];
      count = 1;
    }
  }

  return majority;
};

In this implementation, the function majorityElement finds the majority element by traversing the array using a single pass. It starts by assuming the first element as the majority element and initializes the count to 1.

As it iterates through the array, if the current element matches the assumed majority element, it increments the count. Otherwise, it decrements the count. When the count becomes zero, it means the current majority element cannot be the majority for the rest of the array. In this case, it updates the assumed majority element to the current element and resets the count to 1.

Leave a comment