Majority Element

Easy#169counting

You get an array in which one value fills more than half of the places. Find that value. Our example: [3, 1, 3, 2, 3, 3, 1] — the answer is 3, it appears 4 times out of 7.

input
nums: an array of integers. One of its numbers takes more than half of its places.
returns
That number, the majority element.
constraints
  • 1 ≤ nums.length ≤ 2000
  • −10⁹ ≤ nums[i] ≤ 10⁹
  • one number is there more than nums.length / 2 times
our 9 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @return {number}
 */
function majorityElement(nums) {

}
Ctrl ↵
format
reset

saved in this browser

9 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more hash map problems

Pattern “Hash map” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.