169. Majority Element
Asked at 20Bloomberg75Microsoft70Amazon69Google67Meta59Accenture81tcs72Infosys54Zenefits100Adobe91Odoo89Qualcomm76Autodesk59Cognizant57Morgan Stanley54Oracle52DE Shaw47PayPal42IBM35Goldman Sachs28
Problem
Return the majority element of nums, the value that appears more than ⌊n / 2⌋ times. It is guaranteed to exist.
Example: [2,2,1,1,1,2,2] → 2
Constraints: n ≤ 5·10⁴. Follow-up: O(n) time and O(1) space.
Boyer–Moore voting: keep a candidate and a counter. Same value → +1, different → −1; at 0 adopt the current value. The majority (> n/2) can't be cancelled out.
Complexity: O(n) time, O(1) space.
class Solution:
def majorityElement(self, nums: List[int]) -> int:
cand, cnt = None, 0
for x in nums:
if cnt == 0:
cand = x
cnt += 1 if x == cand else -1
return cand
assert Solution().majorityElement([3, 2, 3]) == 3
assert Solution().majorityElement([2, 2, 1, 1, 1, 2, 2]) == 2
class Solution {
public int majorityElement(int[] nums) {
int cand = 0, cnt = 0;
for (int x : nums) {
if (cnt == 0) cand = x;
cnt += (x == cand) ? 1 : -1;
}
return cand;
}
}
func majorityElement(nums []int) int {
cand, cnt := 0, 0 // Boyer-Moore voting
for _, x := range nums {
if cnt == 0 {
cand = x
}
if x == cand {
cnt++
} else {
cnt--
}
}
return cand
}