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) {
  // Set first element in the variable 'majority'
  let majority = nums[0];
  // Initialize 'count' variable with value 1
  let count = 1;

  // Loop through nums array from index 1
  for (let i = 1; i < nums.length; i++) {
    // if the value of 'majority' is same with element at index i of nums array,
    if (nums[i] === majority) {
      // Increment count
      count++;
    } else {
      // Otherwise, decrement count
      count--;
    }

    // If count is eqaul to 0,
    if (count === 0) {
      // new element which is an element in nums array at index i is assigned in the 'majority' variable
      majority = nums[i];
      // Count is set to 1
      count = 1;
    }
  }

  // return 'majority' variable
  return majority;
};

The time complexity is O(n). The code works by iterating through the array and keeping track of a candidate majority element and its count, and it makes only one pass through the array, so the time complexity is O(n).

Leave a comment