169. Majority Element - Easy

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:
Input: nums [3,2,3]

Output: 3

Constraints:

  • n == nums.length;
  • 1 <= n <= 5 * 10**4
  • -10**9 <= nums[i] <= 10**9
Solution:
var majorityElement = function(nums) {
    const sortedNums = nums.sort();
    return sortedNums.length > 1 ? sortedNums[Math.floor(nums.length / 2)] : sortedNums[0];
}

Thoughts:
Got the answer pretty quickly but struggled to pass the last couple test cases for a while so thats when I had to use the if statement to check the length of the array is greater than 1 or else we can just return the first index value as the answer. I believe it solves the problem in linear time and 0(1) space because sorted it is in 0(n) and then because its an array we can do 0(1) lookup. I'd give my confidence rating a 7.5/10 out of 10.

Comments

Popular posts from this blog

27. Remove Element - Easy

55. Jump Game - Medium

26. Remove Duplicates from Sorted Array - Easy