Majority Element

Boyer-Moore vote — increment count when seeing the candidate, decrement otherwise; reset candidate when count hits 0.

Easy
Time O(n) Space O(1)
LeetCode
2 min read
array boyer-moore voting

Problem#

The majority element appears more than n / 2 times. Find it. Assume it always exists.

Examples#

  • [3,2,3]3.
  • [2,2,1,1,1,2,2]2.

Constraints#

  • 1 <= nums.length <= 5 * 10^4.

Approach#

Boyer-Moore voting: keep a candidate and a count. For each element, if count is 0, adopt it as candidate. Increment count if equal to candidate, decrement otherwise.

Solution#

Majority Element
class Solution {
public:
int majorityElement(vector<int>& nums) {
int candidate = 0, count = 0;
for (int v : nums) {
if (count == 0) candidate = v;
count += (v == candidate) ? 1 : -1;
}
return candidate;
}
};

Editorial#

Each non-majority vote pairs off with a majority vote, canceling. Since the majority count strictly exceeds n/2, at least one majority vote remains after pairing — it’s whatever the candidate ends up as. The algorithm needs no extra memory and runs in one pass.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.