Google | Onsite | Majority Element

3049
Jul 26, 2019
May 13, 2020

Given an array nums of length n and an int k. All the elements are non-negative integers and the same elements are adjacent in the array. Find the majority element. The majority element is any element that appears more than|n/k| times. If there's no majority element return -1.

Example 1:

Input: nums = [1, 1, 1, 1, 3, 4, 0, 0, 0, 0, 0, 9], k = 3
Output: 0
Explanation: n = 12 -> n / k = 12 / 3 = 4. Only 0 appears more than 4 times so return 0.

Example 2:

Input: nums = [1, 1, 1, 1, 3, 4, 0, 0, 0, 0, 9, 9], k = 3
Output: -1
Explanation: There's no element that appears more than 4 times so return -1.
Follow-up

Can you do better than O(n)?

Comments (7)