Majority Element

easy

You're handed an array nums of n integers, and one value is the undisputed majority — it appears more than ⌊n / 2⌋ times, so it fills over half the array. Return that value.

You may assume the majority element always exists, so you never have to handle a 'no winner' case.

For nums = [2, 2, 1, 1, 1, 2, 2] we have n = 7, so half is 3. The value 2 shows up 4 times — strictly more than half — so the answer is 2.

Hints

You only need the single value that appears more than half the time. If every element paired up with a different one and both were thrown away, what kind of value could never be fully removed?
Counting occurrences works, but a hash map costs O(n) memory. Can you get the answer in one pass using just a couple of integer variables?
Keep a candidate and a counter. Matching values bump the counter, different values drop it; when it hits zero, adopt the next value as the candidate. The survivor is the majority — that's Boyer–Moore voting.

Common doubts

This problem guarantees one always exists, so we don't guard against it. If it weren't guaranteed, you'd add a second pass to verify the surviving candidate really appears more than n/2 times.
Every cancellation removes one majority vote and one non-majority vote. There are fewer than n/2 non-majority votes in total, so they run out before the majority (more than n/2) does — at least one majority vote always survives.
No. All three approaches return the value, not a position, and the majority can appear anywhere in any order — the count is all that matters.

Interview follow-ups

That's exactly Boyer–Moore voting: one pass, two integer variables, no extra structures. It's the classic linear-time, constant-space follow-up.
Generalize Boyer–Moore to two candidates and two counters (there can be at most two such values). This is the Misra–Gries idea behind 'Majority Element II' and the > n/k case.

Fun facts

  • Boyer–Moore majority voting was published in 1981 by Robert Boyer and J Strother Moore — the same duo behind the Boyer–Moore string-search algorithm.
  • The cancellation trick generalizes to the Misra–Gries summary, a workhorse for finding frequent items in massive data streams where you can't afford to store every element.

Asked at

AmazonGoogleMicrosoftAdobeBloomberg
Frequently Sometimes Occasionally
Example 1
Input: nums = [3,2,3]
Output: 3
n = 3, so half is 1. The value 3 appears 2 times — more than half.
Example 2
Input: nums = [2,2,1,1,1,2,2]
Output: 2
n = 7, so half is 3. The value 2 appears 4 times — more than half.
Constraints

- n == nums.length - 1 <= n <= 5 * 10^4 - -10^9 <= nums[i] <= 10^9 - The input is generated such that a majority element always exists in the array.

Solve this problem →