Skip to main content
CodeOath
← All problems

Problem

Majority Element

Easy
  • arrays

One value in nums fills more than half of the array. Find it and return it.

Example 1
Input
nums = [7, 3, 7, 7, 1, 7, 3]
Output
7
Explanation

7 appears 4 times out of 7, which is more than half. 3 appears only twice.

Example 2
Input
nums = [5]
Output
5
Explanation

the only element makes up the whole array.

Constraints:

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • a value that occurs more than nums.length / 2 times always exists

Follow-up: counting every value in a map works. Can you do it with constant extra space?

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.